package com.zyzf.coffeepreorder.ui.order

import android.content.res.Configuration
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.fillMaxHeight
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
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.Create
import androidx.compose.material3.Button
import androidx.compose.material3.Card
import androidx.compose.material3.DatePicker
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.ExtendedFloatingActionButton
import androidx.compose.material3.FilledIconButton
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButtonDefaults
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.material3.TimePicker
import androidx.compose.material3.rememberDatePickerState
import androidx.compose.material3.rememberTimePickerState
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.window.Dialog
import androidx.compose.ui.window.DialogProperties
import androidx.navigation.NavController
import com.zyzf.coffeepreorder.database.AppDatabase
import com.zyzf.coffeepreorder.ui.navigation.Screen
import com.zyzf.coffeepreorder.ui.theme.CoffeePreorderTheme
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.withContext
import java.text.SimpleDateFormat
import java.util.Calendar
import java.util.Date
import java.util.Locale

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun Order(navController: NavController?) {
    val openDatePicker = remember { mutableStateOf(false) }
    val openTimePicker = remember { mutableStateOf(false) }
    val calendar = Calendar.getInstance()
    val datePickerState = rememberDatePickerState(initialSelectedDateMillis = calendar.timeInMillis)
    val timePickerState = rememberTimePickerState(is24Hour = true, initialHour = calendar.get(Calendar.HOUR_OF_DAY), initialMinute = calendar.get(Calendar.MINUTE))
    val formatter = SimpleDateFormat("dd.MM.yyyy", Locale.ROOT)
    val context = LocalContext.current
    val sum = remember { mutableStateOf(0.0) }
    LaunchedEffect(Unit) {
        withContext(Dispatchers.IO) {
            sum.value = AppDatabase.getInstance(context).cartDao().getSumInCart()
        }
    }
    Column(Modifier.padding(all = 10.dp), horizontalAlignment = Alignment.CenterHorizontally) {
        Row(modifier = Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.Center,
            verticalAlignment = Alignment.CenterVertically) {
            OutlinedTextField(
                value = formatter.format(Date(datePickerState.selectedDateMillis!!)), onValueChange = {}, readOnly = true,
                label = {
                    Text("Дата")
                }
            )
            Spacer(modifier = Modifier.padding(all = 10.dp))
            FilledIconButton(onClick = { openDatePicker.value = true },
                colors = IconButtonDefaults.filledIconButtonColors(
                    containerColor = MaterialTheme.colorScheme.primaryContainer,
                    contentColor = MaterialTheme.colorScheme.primary,
                )) {
                Icon(imageVector = Icons.Default.Create, contentDescription = "Выбрать дату")
            }
        }
        Row(modifier = Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.Center,
            verticalAlignment = Alignment.CenterVertically) {
            OutlinedTextField(
                value = "${timePickerState.hour}:${timePickerState.minute}", onValueChange = {}, readOnly = true,
                label = {
                    Text("Время")
                }
            )
            Spacer(modifier = Modifier.padding(all = 10.dp))
            FilledIconButton(onClick = { openTimePicker.value = true },
                colors = IconButtonDefaults.filledIconButtonColors(
                    containerColor = MaterialTheme.colorScheme.primaryContainer,
                    contentColor = MaterialTheme.colorScheme.primary,
                )) {
                Icon(imageVector = Icons.Default.Create, contentDescription = "Выбрать время")
            }
        }
        Spacer(modifier = Modifier.padding(all = 20.dp))
        Text(text = "Сумма: ${sum.value}")
    }
    Box(modifier = Modifier.fillMaxSize()) {
        ExtendedFloatingActionButton(
            onClick = { navController?.navigate(Screen.CoffeeList.route) },
            icon = { Icon(Icons.Filled.Add, "Оформить заказ") },
            text = { Text(text = "Оформить заказ") },
            modifier = Modifier
                .align(alignment = Alignment.BottomEnd)
                .padding(all = 20.dp),
            containerColor = MaterialTheme.colorScheme.primaryContainer,
            contentColor = MaterialTheme.colorScheme.primary
        )
    }

    if (openDatePicker.value) {
        Dialog(onDismissRequest = { openDatePicker.value = false },
            properties = DialogProperties(dismissOnBackPress = true, dismissOnClickOutside = true, usePlatformDefaultWidth = false)) {
            Card(
                modifier = Modifier
                    .fillMaxWidth()
                    .fillMaxHeight(0.7f)
                    .padding(16.dp),
                shape = RoundedCornerShape(16.dp),
            ) {
                Column(verticalArrangement = Arrangement.Center, horizontalAlignment = Alignment.End) {
                    Button(
                        onClick = { openDatePicker.value = false },
                        modifier = Modifier.padding(10.dp),
                    ) {
                        Text("Ок")
                    }
                    DatePicker(
                        state = datePickerState,
                        modifier = Modifier.fillMaxSize().padding(10.dp)
                    )
                }
            }
        }
    }

    if (openTimePicker.value) {
        Dialog(onDismissRequest = { openTimePicker.value = false },
            properties = DialogProperties(dismissOnBackPress = true, dismissOnClickOutside = true)) {
            Card(
                modifier = Modifier
                    .fillMaxWidth(1f)
                    .fillMaxHeight(0.55f)
                    .padding(16.dp),
                shape = RoundedCornerShape(16.dp),
            ) {
                Column(verticalArrangement = Arrangement.Center, horizontalAlignment = Alignment.CenterHorizontally) {
                    Button(
                        onClick = { openTimePicker.value = false },
                        modifier = Modifier.padding(10.dp),
                    ) {
                        Text("Ок")
                    }
                    TimePicker(
                        state = timePickerState,
                        modifier = Modifier.fillMaxSize().padding(10.dp)
                    )
                }
            }
        }
    }
}

@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 OrderPreview() {
    CoffeePreorderTheme {
        Surface(
            color = MaterialTheme.colorScheme.background
        ) {
            Order(null)
        }
    }
}