package com.example.myapplication.ui.list

import android.content.res.Configuration
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Delete
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.lifecycle.viewmodel.compose.viewModel
import androidx.navigation.NavController
import androidx.paging.compose.collectAsLazyPagingItems
import androidx.paging.compose.itemContentType
import androidx.paging.compose.itemKey
import com.example.myapplication.database.AppViewModelProvider
import com.example.myapplication.database.room.viewmodel.user.CurrentUserViewModel
import com.example.myapplication.database.room.viewmodel.rent.RentListViewModel
import com.example.myapplication.ui.view.ErroreView
import com.example.myapplication.ui.navigation.Screen
import com.example.myapplication.ui.theme.PmudemoTheme
import kotlinx.coroutines.launch

@Composable
fun RentList(
    navController: NavController?,
    viewModel: RentListViewModel = viewModel(factory = AppViewModelProvider.Factory),
    currentUserViewModel: CurrentUserViewModel = viewModel(factory = AppViewModelProvider.Factory)
) {
    var getUser by remember { mutableStateOf(currentUserViewModel.user) }

    // Проверяем, есть ли у пользователя uid
    if (getUser?.uid != null) {
        viewModel.setUserId(getUser?.uid!!)

        val coroutineScope = rememberCoroutineScope()
        val rentsUiState = viewModel.rentListUiState.collectAsLazyPagingItems()

        LazyColumn(
            modifier = Modifier
                .fillMaxSize()
                .padding(all = 10.dp)
        ) {
            items(
                count = rentsUiState.itemCount,
                key = rentsUiState.itemKey(),
                contentType = rentsUiState.itemContentType()
            ) { index ->
                val rent = rentsUiState[index]
                val rentId = Screen.RentView.route.replace("{id}", rent!!.uid.toString())
                Box(
                    modifier = Modifier
                        .fillMaxWidth()
                        .padding(all = 10.dp)
                        .clickable { navController?.navigate(rentId) }
                        .background(
                            color = MaterialTheme.colorScheme.primary,
                            shape = RoundedCornerShape(16.dp)
                        )
                ) {
                    Row(
                        modifier = Modifier
                            .fillMaxWidth()
                            .padding(8.dp),
                        verticalAlignment = Alignment.CenterVertically,
                        horizontalArrangement = Arrangement.SpaceBetween
                    ) {
                        Text("Аренда №${rent.uid}", color = MaterialTheme.colorScheme.onPrimary)
                        IconButton(
                            onClick = {
                                coroutineScope.launch {
                                    viewModel.deleteRent(rent!!)
                                }
                            }
                        ) {
                            Icon(
                                Icons.Default.Delete,
                                tint = MaterialTheme.colorScheme.onPrimary,
                                contentDescription = "Удалить"
                            )
                        }
                    }
                }
            }
        }
    } else {
        // Пользователь не авторизован, показываем экран с сообщением
        ErroreView()
    }
}

@Preview(name = "Light Mode", showBackground = true, uiMode = Configuration.UI_MODE_NIGHT_NO)
@Preview(name = "Dark Mode", showBackground = true, uiMode = Configuration.UI_MODE_NIGHT_YES)
@Composable
fun RentListPreview() {
    PmudemoTheme {
        Surface(
            color = MaterialTheme.colorScheme.background
        ) {
            RentList(navController = null)
        }
    }
}