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

import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.text.KeyboardOptions
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.OutlinedTextField
import androidx.compose.material3.Text
import androidx.compose.material3.rememberDatePickerState
import androidx.compose.runtime.*
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.unit.dp
import androidx.lifecycle.viewmodel.compose.viewModel
import androidx.navigation.NavController
import com.example.myapplication.R
import com.example.myapplication.database.entities.composeui.AppViewModelProvider
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


@Composable
fun ItemEdit(
    navController: NavController,
    viewModel: ItemEditViewModel = viewModel(factory = AppViewModelProvider.Factory),
) {
    val coroutineScope = rememberCoroutineScope()
    ItemEdit(
        itemUiState = viewModel.itemUiState,
        onClick = {
            coroutineScope.launch {
                viewModel.saveItem()
                navController.popBackStack()
            }
        },
        onUpdate = viewModel::updateUiState
    )
}

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

@OptIn(ExperimentalMaterial3Api::class)
@Composable
private fun ItemEdit(
    itemUiState: ItemUiState,
    onClick: () -> Unit,
    onUpdate: (ItemDetails) -> Unit,
) {
    LazyColumn(
        Modifier
            .fillMaxWidth()
            .padding(all = 10.dp)
    ) {
        item {
            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))
                }

            }

            OutlinedTextField(
                modifier = Modifier.fillMaxWidth(),
                value = itemUiState.itemDetails.weight,
                label = { Text(text = "Вес") },
                onValueChange = {
                    onUpdate(itemUiState.itemDetails.copy(weight = it))
                },
                keyboardOptions = KeyboardOptions.Default.copy(keyboardType = KeyboardType.Number),
                textStyle = MaterialTheme.typography.bodyLarge.copy(
                    color = MaterialTheme.colorScheme.onSecondary
                )
            )
            OutlinedTextField(
                modifier = Modifier.fillMaxWidth(),
                value = itemUiState.itemDetails.maxCount.toString(),
                onValueChange = { newValue ->
                    val parsedMaxCount = newValue.toIntOrNull() ?: 0 // Преобразование в Int
                    onUpdate(itemUiState.itemDetails.copy(maxCount = parsedMaxCount))
                },
                label = { Text(text = "Количество") },
                keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number),
                textStyle = MaterialTheme.typography.bodyLarge.copy(
                    color = MaterialTheme.colorScheme.onSecondary
                )
            )
            Button(
                onClick = onClick,
                enabled = itemUiState.isEntryValid,
                shape = MaterialTheme.shapes.small,
                modifier = Modifier.fillMaxWidth()
            ) {
                Text(text = stringResource(R.string.Save_button))
            }
        }
    }
}