package com.example.tasks.screens

import android.widget.Toast
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.gestures.detectTapGestures
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
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.height
import androidx.compose.foundation.layout.offset
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.DateRange
import androidx.compose.material.icons.filled.KeyboardArrowLeft
import androidx.compose.material3.Button
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.DropdownMenuItem
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.ExposedDropdownMenuBox
import androidx.compose.material3.ExposedDropdownMenuDefaults
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Text
import androidx.compose.material3.TextFieldDefaults
import androidx.compose.runtime.Composable
import androidx.compose.runtime.derivedStateOf
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.geometry.Size
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.layout.onGloballyPositioned
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalFocusManager
import androidx.compose.ui.platform.LocalSoftwareKeyboardController
import androidx.compose.ui.platform.testTag
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.compose.ui.unit.toSize
import androidx.navigation.NavController
import com.example.tasks.auxiliary.CustomText
import com.example.tasks.model.Task
import com.example.tasks.model.User
import com.example.tasks.navigation.Screen
import com.example.tasks.ui.theme.SFPro
import com.google.firebase.Firebase
import com.google.firebase.firestore.firestore
import com.vanpra.composematerialdialogs.MaterialDialog
import com.vanpra.composematerialdialogs.datetime.date.datepicker
import com.vanpra.composematerialdialogs.rememberMaterialDialogState
import java.time.LocalDate
import java.time.format.DateTimeFormatter

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun AddTask(
    division: String,
    surname: String,
    name: String,
    patronymic: String,
    navController: NavController
) {

    val list = remember {
        mutableStateOf(emptyList<Task>())
    }

    val task = remember {
        mutableStateOf("")
    }
    val padding = 10.dp
    var pickedDate by remember { mutableStateOf(LocalDate.now()) }
    var pickedDateEnd by remember { mutableStateOf(LocalDate.now()) }
    val formattedDate by remember {
        derivedStateOf {
            DateTimeFormatter
                .ofPattern("dd.MM.yyyy")
                .format(pickedDate)
        }
    }
    val formattedDateEnd by remember {
        derivedStateOf {
            DateTimeFormatter
                .ofPattern("dd.MM.yyyy")
                .format(pickedDateEnd)
        }
    }
    val keyboardController = LocalSoftwareKeyboardController.current
    val focusManager = LocalFocusManager.current
    val dateDialogState = rememberMaterialDialogState()
    val dateDialogStateEnd = rememberMaterialDialogState()
    val context = LocalContext.current
    val fs = Firebase.firestore
    var expandedStaff by remember {
        mutableStateOf(false)
    }
    var textFiledSize by remember {
        mutableStateOf(Size.Zero)
    }
    val listStaff = remember {
        mutableStateOf(emptyList<User>())
    }
    var selectedStaff by remember {
        mutableStateOf("")
    }
    var selectedStaffSurname by remember {
        mutableStateOf("")
    }
    var selectedStaffName by remember {
        mutableStateOf("")
    }
    var selectedStaffPatronymic by remember {
        mutableStateOf("")
    }
    fs.collection("users")
        .whereNotEqualTo(
            "post", "Начальник"
        ).get()
        .addOnCompleteListener {
            if (it.isSuccessful) {
                listStaff.value = it.result.toObjects(User::class.java)
            }
        }

    fs.collection("tasks").orderBy("number").get()
        .addOnCompleteListener { t ->
            if (t.isSuccessful) {
                list.value = t.result.toObjects(Task::class.java)
            }
        }
    listStaff.value.filter { it.division == division }
    Column(
        modifier = Modifier
            .fillMaxSize()
            .padding(20.dp)
            .padding(top = 30.dp)
            .pointerInput(Unit) {
                detectTapGestures(onTap = {
                    keyboardController?.hide()
                    focusManager.clearFocus()
                })
            }
            .background(MaterialTheme.colorScheme.background),
        verticalArrangement = Arrangement.Top,
        horizontalAlignment = Alignment.Start
    ) {
        Row(
            modifier = Modifier
                .fillMaxWidth(),
            horizontalArrangement = Arrangement.Start,
            verticalAlignment = Alignment.CenterVertically
        ) {
            Button(
                onClick = {
                    navController.navigate(
                        Screen.AppNavigationChief.withArg(
                            surname,
                            name,
                            patronymic,
                            division
                        )
                    )

                },
                shape = RoundedCornerShape(size = 8.dp),
                colors = ButtonDefaults.buttonColors(
                    containerColor = Color(0xFFF5F5F9)
                ),

                modifier = Modifier
                    .width(32.dp)
                    .height(32.dp), contentPadding = PaddingValues(1.dp)
            )
            {
                Icon(
                    imageVector = Icons.Filled.KeyboardArrowLeft,
                    contentDescription = "Назад",
                    tint = Color.Black,
                    modifier = Modifier.size(20.dp)
                )
            }
            Spacer(modifier = Modifier.width(10.dp))
            Text(
                text = "Поставить задачу",
                fontSize = 30.sp,
                fontFamily = SFPro,
                fontWeight = FontWeight.Bold,
                color = MaterialTheme.colorScheme.onBackground,
                textAlign = TextAlign.Center
            )
        }


        Spacer(modifier = Modifier.height(50.dp))
        Row(
            modifier = Modifier
                .fillMaxWidth()
                .padding(horizontal = 10.dp),
            horizontalArrangement = Arrangement.SpaceBetween,
            verticalAlignment = Alignment.CenterVertically
        ) {
            Text(
                text = "Исполнитель:",
                Modifier
                    .weight(0.5f),
                fontWeight = FontWeight.Medium,
                fontFamily = SFPro,
                fontSize = 14.sp,
                color = MaterialTheme.colorScheme.onBackground
            )
            ExposedDropdownMenuBox(
                modifier = Modifier
                    .width(200.dp)
                    .testTag("menu"),
                expanded = expandedStaff,
                onExpandedChange = { expandedStaff = !expandedStaff },
            ) {
                OutlinedTextField(
                    value = selectedStaff.ifBlank {
                        "Выберете сотрудника"
                    },
                    onValueChange = {},
                    readOnly = true,
                    colors = TextFieldDefaults.textFieldColors(
                        containerColor = Color(0xFF5178FF),
                        disabledTextColor = Color.White,
                        focusedTextColor = Color.White,
                        disabledIndicatorColor = Color.Transparent,
                        focusedIndicatorColor = Color.Transparent,
                        unfocusedIndicatorColor = Color.Transparent
                    ),
                    textStyle = TextStyle(
                        color = Color.White,
                        fontSize = 15.sp,
                        fontFamily = SFPro,
                        fontWeight = FontWeight.Medium,
                        textAlign = TextAlign.Center
                    ),
                    modifier = Modifier
                        .menuAnchor()
                        .border(0.dp, Color.Transparent, RoundedCornerShape(0.dp))
                        .onGloballyPositioned { coordinates ->
                            textFiledSize = coordinates.size.toSize()
                        }

                )

                ExposedDropdownMenu(
                    expanded = expandedStaff,
                    onDismissRequest = { expandedStaff = true }
                ) {
                    listStaff.value.forEachIndexed { index, text ->
                        DropdownMenuItem(
                            text = {
                                Text(text = text.surname + " " + text.name[0] + "." + text.patronymic[0] + ".")
                            },
                            onClick = {
                                selectedStaff =
                                    listStaff.value[index].surname + " " + listStaff.value[index].name[0] + "." + listStaff.value[index].patronymic[0] + "."
                                selectedStaffName = listStaff.value[index].name
                                selectedStaffSurname = listStaff.value[index].surname
                                selectedStaffPatronymic = listStaff.value[index].patronymic
                                expandedStaff = false


                            },
                            modifier = Modifier.testTag("staff"),
                            contentPadding = ExposedDropdownMenuDefaults.ItemContentPadding
                        )
                    }
                }
            }
        }

        Spacer(modifier = Modifier.height(30.dp))


        Row(
            modifier = Modifier
                .fillMaxWidth()
                .padding(horizontal = 10.dp),
            horizontalArrangement = Arrangement.SpaceBetween,
            verticalAlignment = Alignment.CenterVertically
        ) {
            Text(
                text = "Дата начала:",
                Modifier
                    .weight(0.5f),
                fontWeight = FontWeight.Medium,
                fontFamily = SFPro,
                fontSize = 14.sp,
                color = MaterialTheme.colorScheme.onBackground
            )
            Button(
                onClick = { dateDialogState.show() }, modifier = Modifier
                    .height(height = 56.dp)
                    .width(width = 200.dp)
                    .testTag("date2"),
                shape = RoundedCornerShape(size = 10.dp),
                colors = ButtonDefaults.buttonColors(
                    containerColor = Color(0XFFF5F5F9),
                    contentColor = Color(0XFF40484d)
                )
            ) {
                Icon(
                    Icons.Filled.DateRange,
                    contentDescription = "Дата начала",
                    modifier = Modifier
                        .offset(x = -padding)
                        .padding(end = 2.dp)
                )
                Text(
                    formattedDate.toString(),
                    fontSize = 15.sp,
                    fontFamily = SFPro,
                    fontWeight = FontWeight.Normal,
                    color = Color.Black,
                    modifier = Modifier.fillMaxWidth(),
                    textAlign = TextAlign.Start
                )


            }

        }

        Spacer(modifier = Modifier.height(30.dp))


        Row(
            modifier = Modifier
                .fillMaxWidth()
                .padding(horizontal = 10.dp),
            horizontalArrangement = Arrangement.SpaceBetween,
            verticalAlignment = Alignment.CenterVertically
        ) {
            Text(
                text = "Дата конца:",
                Modifier
                    .weight(0.5f),
                fontWeight = FontWeight.Medium,
                fontFamily = SFPro,
                fontSize = 14.sp,
                color = MaterialTheme.colorScheme.onBackground
            )

            Button(
                onClick = { dateDialogStateEnd.show() }, modifier = Modifier
                    .height(height = 56.dp)
                    .width(width = 200.dp)
                    .testTag("date1"),
                shape = RoundedCornerShape(size = 10.dp),
                colors = ButtonDefaults.buttonColors(
                    containerColor = Color(0XFFF5F5F9),
                    contentColor = Color(0XFF40484d)
                )
            ) {
                Icon(
                    Icons.Filled.DateRange,
                    contentDescription = "Дата конца",
                    modifier = Modifier
                        .offset(x = -padding)
                        .padding(end = 2.dp)

                )
                Text(
                    formattedDateEnd.toString(),
                    fontSize = 15.sp,
                    fontFamily = SFPro,
                    fontWeight = FontWeight.Normal,
                    color = Color.Black,
                    modifier = Modifier.fillMaxWidth(),
                    textAlign = TextAlign.Start
                )


            }

        }
        Spacer(modifier = Modifier.height(30.dp))

        Row(
            modifier = Modifier
                .fillMaxWidth()
                .padding(horizontal = 10.dp),
            horizontalArrangement = Arrangement.SpaceBetween,
            verticalAlignment = Alignment.CenterVertically
        ) {
            Text(
                text = "Задание:",
                Modifier
                    .weight(0.5f),
                fontWeight = FontWeight.Medium,
                fontFamily = SFPro,
                fontSize = 14.sp,
                color = MaterialTheme.colorScheme.onBackground
            )

            Box(modifier = Modifier.fillMaxWidth(0.67f)) {
                CustomText(
                    search = task.value,
                    onValueChange = { task.value = it },
                    focusManager = focusManager
                )
            }

        }

        Spacer(modifier = Modifier.height(30.dp))
        Button(
            onClick = {
                if (selectedStaff == "" || task.value.isEmpty()) {
                    Toast.makeText(context, "Заполните все поля", Toast.LENGTH_SHORT).show()
                } else {
                    fs.collection("tasks")
                        .document().set(
                            Task(
                                selectedStaffSurname,
                                selectedStaffName,
                                selectedStaffPatronymic,
                                pickedDate.toString(),
                                pickedDateEnd.toString(),
                                task = task.value,
                                author = "$surname $name $patronymic",
                                number = list.value.last().number + 1,
                                done = "Новая"
                            )
                        ).addOnCompleteListener {
                            if (it.isSuccessful) {
                                navController.navigate(
                                    Screen.AppNavigationChief.withArg(
                                        surname,
                                        name,
                                        patronymic,
                                        division
                                    )
                                )
                            } else {
                                Toast.makeText(context, "Не удалось записать", Toast.LENGTH_SHORT)
                                    .show()
                            }
                        }
                }
            },

            modifier = Modifier
                .padding(top = 20.dp)
                .width(width = 500.dp)
                .height(height = 56.dp)
                .testTag("button_add"),
            shape = RoundedCornerShape(size = 10.dp),
            colors = ButtonDefaults.buttonColors(

                containerColor = Color(0XFF990000),
                contentColor = Color.White
            )
        ) {
            Text(
                text = "Сохранить",
                fontSize = 20.sp,
                fontWeight = FontWeight.W900,
                fontFamily = SFPro
            )
        }


    }
    MaterialDialog(
        dialogState = dateDialogState,
        buttons = {
            positiveButton(text = "Ok")
            negativeButton("cancel")
        })
    {
        datepicker(
            initialDate = LocalDate.now()
        ) {
            pickedDate = it

        }
    }
    MaterialDialog(
        dialogState = dateDialogStateEnd,
        buttons = {
            positiveButton(text = "Ok")
            negativeButton("cancel")
        })
    {
        datepicker(
            initialDate = LocalDate.now()
        ) {
            pickedDateEnd = it

        }
    }
}



