package com.example.myapplication.database.entities.composeui

import android.graphics.BitmapFactory
import androidx.compose.animation.AnimatedVisibility
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Add
import androidx.compose.material.icons.filled.Delete
import androidx.compose.material.icons.filled.Edit
import androidx.compose.material.icons.filled.Info
import androidx.compose.material3.FloatingActionButton
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Scaffold
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.draw.clip
import androidx.compose.ui.draw.shadow
import androidx.compose.ui.graphics.asImageBitmap
import androidx.compose.ui.unit.dp
import androidx.lifecycle.viewmodel.compose.viewModel
import androidx.navigation.NavController
import androidx.paging.compose.LazyPagingItems
import androidx.paging.compose.collectAsLazyPagingItems
import com.example.myapplication.database.AppViewModelProvider
import com.example.myapplication.database.room.model.bike.Bike
import com.example.myapplication.database.room.viewmodel.user.CurrentUserViewModel
import com.example.myapplication.ui.navigation.Screen
import com.example.myapplication.ui.view.ErroreView
import kotlinx.coroutines.launch

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

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

        Scaffold(
            topBar = {},
            floatingActionButton = {
                if(getUser?.role == "admin") {
                    Box(
                        contentAlignment = Alignment.Center
                    ) {
                        FloatingActionButton(
                            onClick = {
                                val route = Screen.BikeEdit.route.replace("{id}", 0.toString())
                                navController.navigate(route)
                            },
                            modifier = Modifier.fillMaxWidth(0.92f).align(Alignment.BottomCenter),
                            containerColor = MaterialTheme.colorScheme.primary
                        ) {
                            Icon(
                                Icons.Filled.Add,
                                "Добавить",
                                tint = MaterialTheme.colorScheme.onPrimary
                            )
                        }
                    }
                }
            }
        ) { innerPadding ->
            BikeList(
                currentUserViewModel = currentUserViewModel,
                modifier = Modifier
                    .padding(innerPadding)
                    .fillMaxSize(),
                pagingBike = bikePagingItems,
                onClick = { uid: Int ->
                    val route = Screen.BikeView.route.replace("{id}", uid.toString())
                    navController.navigate(route)
                },
                onDeleteClick = { bike: Bike ->
                    coroutineScope.launch {
                        viewModel.deleteBike(bike)
                    }
                },
                onEditClick = { uid: Int ->
                    val route = Screen.BikeEdit.route.replace("{id}", uid.toString())
                    navController.navigate(route)
                },
            )
        }
    } else {
        ErroreView()
    }
}

@Composable
private fun BikeList(
    modifier: Modifier = Modifier,
    pagingBike: LazyPagingItems<Bike>,
    onClick: (uid: Int) -> Unit,
    onDeleteClick: (bike: Bike) -> Unit,
    onEditClick: (bike: Int) -> Unit,
    currentUserViewModel: CurrentUserViewModel = viewModel(factory = AppViewModelProvider.Factory)
) {
    var getUser by remember { mutableStateOf(currentUserViewModel.user) }

    Column(
        modifier = modifier
    ) {
        LazyColumn(
            modifier = Modifier
                .fillMaxSize()
                .padding(all = 10.dp)
                .then(if (getUser?.role == "admin") Modifier.padding(bottom = 72.dp) else Modifier)
        ) {
            items(pagingBike.itemCount) { index ->
                val bike = pagingBike[index]
                if (bike != null) {
                    BikeListItem(
                        currentUserViewModel = currentUserViewModel,
                        bike = bike,
                        modifier = Modifier
                            .padding(vertical = 7.dp)
                            //.clickable { onClick(bike.uid) }
                            .background(
                                color = MaterialTheme.colorScheme.primary,
                                shape = RoundedCornerShape(16.dp)
                            ),
                        onDeleteClick = onDeleteClick,
                        onEditClick = onEditClick,
                        onClick = onClick
                    )
                }
            }
        }
    }
}


@Composable
private fun BikeListItem(
    currentUserViewModel: CurrentUserViewModel = viewModel(factory = AppViewModelProvider.Factory),
    bike: Bike,
    modifier: Modifier = Modifier,
    onDeleteClick: (bike: Bike) -> Unit,
    onClick: (uid: Int) -> Unit,
    onEditClick: (bike: Int) -> Unit
) {
    var getUser by remember { mutableStateOf(currentUserViewModel.user) }
    var isExpanded by remember { mutableStateOf(false) } // Состояние для определения, раскрыта ли дополнительная информация о велосипеде

    Box(
        modifier = modifier
            .clip(RoundedCornerShape(8.dp))
            .shadow(4.dp)
            .padding(8.dp)
            .clickable {
                isExpanded = !isExpanded
            } // Добавляем обработчик нажатия для раскрытия/скрытия дополнительной информации
    ) {
        Column(Modifier.padding(8.dp)) {
            Row(
                verticalAlignment = Alignment.CenterVertically,
                horizontalArrangement = Arrangement.spacedBy(8.dp)
            ) {
                if (bike.image != null)
                    Box(
                        modifier = Modifier
                            .size(90.dp)
                            .padding(4.dp)
                            .border(
                                width = 1.dp,
                                color = MaterialTheme.colorScheme.secondary
                            ) // Добавляем рамку
                    ) {
                        Image(
                            bitmap = BitmapFactory.decodeByteArray(
                                bike.image,
                                0,
                                bike.image.size
                            ).asImageBitmap(),
                            contentDescription = null,
                            modifier = Modifier.fillMaxSize()
                        )
                    }

                Text(
                    "${bike.name}",
                    color = MaterialTheme.colorScheme.secondary,
                    //style = MaterialTheme.typography.h6
                )

                // Добавляем пустое пространство для разделения текста и кнопок

                Spacer(modifier = Modifier.weight(1f))
                if (getUser?.role == "admin") {
                    IconButton(
                        onClick = { onEditClick(bike.uid) },
                        modifier = Modifier.size(24.dp)
                    ) {
                        Icon(
                            imageVector = Icons.Default.Edit,
                            contentDescription = "Редактировать",
                            tint = MaterialTheme.colorScheme.secondary,
                        )
                    }
                }
                IconButton(
                    onClick = { onClick(bike.uid) },
                    modifier = Modifier.size(24.dp)
                ) {
                    Icon(
                        imageVector = Icons.Default.Info,
                        contentDescription = "Информация",
                        tint = MaterialTheme.colorScheme.secondary,
                    )
                }
                if (getUser?.role == "admin") {
                    IconButton(
                        onClick = { onDeleteClick(bike) },
                        modifier = Modifier.size(24.dp)
                    ) {
                        Icon(
                            imageVector = Icons.Default.Delete,
                            contentDescription = "Удалить",
                            tint = MaterialTheme.colorScheme.secondary,
                        )
                    }
                }
            }
            AnimatedVisibility(visible = isExpanded) { // Анимированная видимость для дополнительной информации
                Text(
                    text = bike.description,
                    color = MaterialTheme.colorScheme.secondary,
                    //style = MaterialTheme.typography.body2,
                    modifier = Modifier.padding(top = 8.dp)
                )
            }
        }
    }
}
