package com.example.tasks.screens

import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
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.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.layout.width
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material3.Button
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.Card
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.testTag
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.navigation.NavController
import com.example.tasks.R
import com.example.tasks.model.Task
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 java.time.LocalDate
import java.time.temporal.ChronoUnit

@Composable
fun WorkingStaff(name: String, surname: String, patronymic: String, navController: NavController) {
    val fs = Firebase.firestore
    val list = remember {
        mutableStateOf(emptyList<Task>())
    }
    val list2 = remember {
        mutableStateOf(emptyList<Task>())
    }
    val listBool = remember {
        mutableListOf<String>()
    }
    var id = ""
    Column(
        modifier = Modifier
            .fillMaxSize()
            .padding(20.dp)
            .padding(top = 40.dp)
            .background(MaterialTheme.colorScheme.background),
        verticalArrangement = Arrangement.Top,
        horizontalAlignment = Alignment.Start
    ) {
        Row(
            modifier = Modifier.fillMaxWidth(),
            horizontalArrangement = Arrangement.SpaceBetween,
            verticalAlignment = Alignment.CenterVertically
        ) {
            Text(
                text = "В работе",
                fontSize = 35.sp,
                fontFamily = SFPro,
                fontWeight = FontWeight.Bold,
                color = MaterialTheme.colorScheme.onBackground
            )
            Image(
                painter = painterResource(id = R.drawable.exit),
                contentDescription = "",
                modifier = Modifier
                    .size(25.dp)
                    .clickable { navController.navigate(Screen.Start.route) }
            )
        }

        fs.collection("tasks")
            .whereEqualTo(
                "surname", surname
            ).whereEqualTo(
                "name", name
            ).whereEqualTo(
                "patronymic", patronymic
            ).get()
            .addOnCompleteListener {
                if (it.isSuccessful) {
                    list.value = it.result.toObjects(Task::class.java)
                    list.value.forEach { done ->
                        listBool.add(done.done)
                    }

                }
            }

        Spacer(modifier = Modifier.height(30.dp))
        if (list.value.isNotEmpty()) {
            LazyColumn(
                modifier = Modifier
                    .fillMaxSize()
            ) {
                items(list.value) { task ->
                    val startDate = LocalDate.parse(task.start_date)
                    val endDate = LocalDate.parse(task.end_date)
                    val dayStart = ChronoUnit.DAYS.between(startDate, LocalDate.now())
                    val dayEnd = ChronoUnit.DAYS.between(LocalDate.now(), endDate)
                    if (dayStart >= 0 && dayEnd >= 0 && task.done == "В работе") {
                        Card(
                            modifier = Modifier
                                .fillMaxWidth()
                                .padding(bottom = 30.dp)

                        ) {

                            Column(modifier = Modifier.fillMaxWidth()) {
                                Row(modifier = Modifier.fillMaxWidth()) {
                                    TableCellHead(text = "Исполнитель: ")
                                    TableCell(text = task.surname + " " + task.name[0] + "." + task.patronymic[0] + ".")
                                }
                                Row(modifier = Modifier.fillMaxWidth()) {
                                    TableCellHead(text = "Дата начала: ")
                                    TableCell(text = task.start_date)
                                }
                                Row(modifier = Modifier.fillMaxWidth()) {
                                    TableCellHead(text = "Дата конца: ")
                                    TableCell(text = task.end_date)
                                }
                                Row(modifier = Modifier.fillMaxWidth()) {
                                    TableCellHead(text = "Задание: ")
                                    TableCell(text = task.task)
                                }
                                val index = list.value.indexOf(task)

                                Button(
                                    modifier = Modifier
                                        .padding(top = 20.dp)
                                        .width(width = 500.dp)
                                        .height(height = 56.dp)
                                        .testTag("change_status$index"),
                                    onClick = {
                                        listBool[list.value.indexOf(task)] = "Выполнено"
                                        fs.collection("tasks")
                                            .whereEqualTo("number", task.number)
                                            .get()
                                            .addOnSuccessListener { result ->
                                                for (document in result) {
                                                    val documentID = document.id
                                                    id = documentID
                                                    fs.collection("tasks").document(id)
                                                        .update(
                                                            "done",
                                                            listBool[list.value.indexOf(task)]
                                                        )

                                                }
                                            }
                                        fs.collection("tasks")
                                            .whereEqualTo(
                                                "surname", surname
                                            ).whereEqualTo(
                                                "name", name
                                            ).whereEqualTo(
                                                "patronymic", patronymic
                                            )
                                            .whereEqualTo("done", false).get()
                                            .addOnCompleteListener { t ->
                                                if (t.isSuccessful) {
                                                    list.value =
                                                        t.result.toObjects(Task::class.java)
                                                    list.value.forEach { done ->
                                                        listBool.add(done.done)
                                                    }
                                                }
                                            }
                                    },
                                    shape = RoundedCornerShape(size = 10.dp),
                                    colors = ButtonDefaults.buttonColors(
                                        containerColor = Color(0xFF5178FF),
                                        contentColor = Color.White
                                    )
                                ) {
                                    Text(
                                        text = "Выполнить",
                                        fontSize = 20.sp,
                                        fontWeight = FontWeight.W900,
                                        fontFamily = SFPro
                                    )
                                }


                            }
                        }
                    }
                }
            }
        } else {
            Column(
                modifier = Modifier.fillMaxSize(),
                verticalArrangement = Arrangement.Center,
                horizontalAlignment = Alignment.CenterHorizontally
            ) {
                CircularProgressIndicator()
            }
        }


    }
}