package com.example.myapplication.ui.edit

import android.annotation.SuppressLint
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.text.BasicTextField
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.foundation.verticalScroll
import androidx.compose.material3.Button
import androidx.compose.material3.DatePicker
import androidx.compose.material3.DatePickerDefaults
import androidx.compose.material3.DisplayMode
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.material3.rememberDatePickerState
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.input.ImeAction
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.lifecycle.viewmodel.compose.viewModel
import androidx.navigation.NavController
import com.example.myapplication.database.AppViewModelProvider
import com.example.myapplication.database.room.viewmodel.user.CurrentUserViewModel
import com.example.myapplication.database.room.viewmodel.item.ItemDetails
import com.example.myapplication.database.room.viewmodel.item.ItemEditViewModel
import com.example.myapplication.database.room.viewmodel.item.ItemUiState
import kotlinx.coroutines.launch
import org.threeten.bp.Instant
import org.threeten.bp.LocalDateTime
import org.threeten.bp.LocalTime
import org.threeten.bp.ZoneId
import org.threeten.bp.ZoneOffset
import java.text.ParseException
import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale


@Composable
fun ItemEdit(
    navController: NavController,
    viewModel: ItemEditViewModel = viewModel(factory = AppViewModelProvider.Factory),
    currentUserViewModel: CurrentUserViewModel = viewModel(factory = AppViewModelProvider.Factory)
) {
    val coroutineScope = rememberCoroutineScope()
    var getUser by remember { mutableStateOf(currentUserViewModel.user) }

    if(getUser?.role == "admin"){
    ItemEdit(
        itemUiState = viewModel.itemUiState,
        onClick = {
            coroutineScope.launch {
                viewModel.saveItem()
                navController.popBackStack()
            }
        },
        onUpdate = viewModel::updateUiState
    )
    }
    else{
        Column(
            modifier = Modifier
                .fillMaxSize()
                .padding(16.dp),
            verticalArrangement = Arrangement.Center,
            horizontalAlignment = Alignment.CenterHorizontally
        ) {
            Column(
                modifier = Modifier
                    .fillMaxSize()
                    .weight(1f), // Занимает все доступное пространство, кроме кнопки
                verticalArrangement = Arrangement.Center,
                horizontalAlignment = Alignment.CenterHorizontally
            ) {
                Text("На данный момент страница не доступна.", fontWeight = FontWeight.Bold)
                Spacer(modifier = Modifier.height(8.dp))
                Text("У вашего аккаунта не достаточно прав.")
            }

            Button(
                onClick = {
                    coroutineScope.launch {
                        navController.popBackStack()
                    }
                },
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(8.dp)
            ) {
                Text("Выйти")
            }
        }

    }
}

fun Long.toLocalDate(): org.threeten.bp.LocalDate {
    val instant = Instant.ofEpochMilli(this)
    return instant.atZone(ZoneId.systemDefault()).toLocalDate()
}

@SuppressLint("SuspiciousIndentation")
@OptIn(ExperimentalMaterial3Api::class)
@Composable
private fun ItemEdit(
    itemUiState: ItemUiState,
    onClick: () -> Unit,
    onUpdate: (ItemDetails) -> Unit,
) {

    Column(
        modifier = Modifier
            .verticalScroll(rememberScrollState())
            .padding(16.dp)
    ) {
        Row(
            modifier = Modifier.fillMaxWidth(),
            horizontalArrangement = Arrangement.SpaceBetween
        ) {
            Column(
                modifier = Modifier
                    //.width(180.dp) // Adjust the width as needed
                    .fillMaxHeight()
                    .padding(8.dp),
                horizontalAlignment = Alignment.CenterHorizontally,
                verticalArrangement = Arrangement.Center
            ) {
                Text(
                    text = "Вес",
                    textAlign = TextAlign.Center,
                )
                Spacer(modifier = Modifier.height(4.dp))
                BasicTextField(
                    value = itemUiState.itemDetails.weight,
                    onValueChange = { onUpdate(itemUiState.itemDetails.copy(weight = it)) },
                    modifier = Modifier
                        .fillMaxWidth()
                        .size(36.dp)
                        .background(
                            MaterialTheme.colorScheme.onBackground,
                            RoundedCornerShape(18.dp)
                        )
                        .padding(start = 13.dp, top = 8.dp),
                    textStyle = TextStyle(color = MaterialTheme.colorScheme.background),
                )
                Spacer(modifier = Modifier.height(4.dp))
                Text(
                    text = "Радиус",
                    textAlign = TextAlign.Center,
                )
                Spacer(modifier = Modifier.height(4.dp))
                BasicTextField(
                    value = itemUiState.itemDetails.radius,
                    onValueChange = { onUpdate(itemUiState.itemDetails.copy(radius = it)) },
                    modifier = Modifier
                        .fillMaxWidth()
                        .size(36.dp)
                        .background(
                            MaterialTheme.colorScheme.onBackground,
                            RoundedCornerShape(18.dp)
                        )
                        .padding(start = 13.dp, top = 8.dp),
                    textStyle = TextStyle(color = MaterialTheme.colorScheme.background),
                )
                Spacer(modifier = Modifier.height(4.dp))
                Text(
                    text = "Цвет",
                    textAlign = TextAlign.Center,
                )
                Spacer(modifier = Modifier.height(4.dp))
                BasicTextField(
                    value = itemUiState.itemDetails.colorbike,
                    onValueChange = { onUpdate(itemUiState.itemDetails.copy(colorbike = it)) },
                    modifier = Modifier
                        .fillMaxWidth()
                        .size(36.dp)
                        .background(
                            MaterialTheme.colorScheme.onBackground,
                            RoundedCornerShape(18.dp)
                        )
                        .padding(start = 13.dp, top = 8.dp),
                    textStyle = TextStyle(color = MaterialTheme.colorScheme.background),
                    keyboardOptions = KeyboardOptions(
                        keyboardType = KeyboardType.Text,
                        imeAction = ImeAction.Done
                    )
                )
                Spacer(modifier = Modifier.height(4.dp))
                Text(
                    text = "Количество",
                    textAlign = TextAlign.Center,
                )
                Spacer(modifier = Modifier.height(4.dp))
                BasicTextField(
                    value = itemUiState.itemDetails.maxCount.toString(),
                    onValueChange = { newValue ->
                        val parsedMaxCount = newValue.toIntOrNull() ?: 0 // Преобразование в Int
                        onUpdate(itemUiState.itemDetails.copy(maxCount = parsedMaxCount))
                    },
                    modifier = Modifier
                        .fillMaxWidth()
                        .size(36.dp)
                        .background(
                            MaterialTheme.colorScheme.onBackground,
                            RoundedCornerShape(18.dp)
                        )
                        .padding(start = 13.dp, top = 8.dp),
                    textStyle = TextStyle(color = MaterialTheme.colorScheme.background),
                )
                Spacer(modifier = Modifier.height(4.dp))
                if (itemUiState.itemDetails.dateTime != LocalDateTime.MIN) {
                    val selectedDateMillis =
                        itemUiState.itemDetails.dateTime.toInstant(ZoneOffset.UTC).toEpochMilli()

                    val dateState = rememberDatePickerState(
                        initialDisplayMode = DisplayMode.Input,
                        initialSelectedDateMillis = selectedDateMillis
                    )
                    /*         Surface(
                                 tonalElevation = 6.dp,
                                 color = MaterialTheme.colorScheme.primary
                             ) {*/
                    DatePicker(
                        state = dateState,
                        modifier = Modifier.padding(16.dp),
                        colors = DatePickerDefaults.colors(
                            dayContentColor = MaterialTheme.colorScheme.primary,
                        )
                    )
                    // }
                    val selectedDate = dateState.selectedDateMillis?.toLocalDate()
                    if (selectedDate != null) {
                        val resultDateTime = LocalDateTime.of(selectedDate, LocalTime.MIDNIGHT)
                        onUpdate(itemUiState.itemDetails.copy(dateTime = resultDateTime))
                    }
                } else {
                    val dateState = rememberDatePickerState(
                        initialDisplayMode = DisplayMode.Input
                    )
                    /*         Surface(
                                 tonalElevation = 6.dp,
                                 color = MaterialTheme.colorScheme.primary
                             ) {*/
                    DatePicker(
                        state = dateState,
                        modifier = Modifier.padding(16.dp),
                        colors = DatePickerDefaults.colors(
                            dayContentColor = MaterialTheme.colorScheme.primary,
                        )
                    )
                    // }
                    val selectedDate = dateState.selectedDateMillis?.toLocalDate()
                    if (selectedDate != null) {
                        val resultDateTime = LocalDateTime.of(selectedDate, LocalTime.MIDNIGHT)
                        onUpdate(itemUiState.itemDetails.copy(dateTime = resultDateTime))
                    }

                }
                Button(
                    onClick = onClick,
                    enabled = itemUiState.isEntryValid,
                    shape = MaterialTheme.shapes.small,
                    modifier = Modifier.fillMaxWidth()
                ) {
                    Text(text = "Сохранить")
                }
            }
        }
    }
}

private fun parseDate(dateString: MutableState<String>): Date? {
    return try {
        // Use SimpleDateFormat or any other method to parse the string into a Date object
        // For example:
        SimpleDateFormat("yyyy", Locale.getDefault()).parse(dateString.toString())
    } catch (e: ParseException) {
        // Handle parsing error
        null
    }
}
