package com.example.myapplication.ui.list

import androidx.compose.animation.AnimatedVisibility
import androidx.compose.foundation.BorderStroke
import androidx.compose.foundation.background
import androidx.compose.foundation.border
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.layout.width
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.text.BasicTextField
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.AlertDialog
import androidx.compose.material3.Button
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.Card
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.text.TextStyle
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.lifecycle.viewmodel.compose.viewModel
import androidx.navigation.NavController
import com.example.myapplication.R
import com.example.myapplication.api.report.remote.ReportRemote
import com.example.myapplication.database.AppViewModelProvider
import com.example.myapplication.database.room.viewmodel.rent.ReportViewModel
import com.example.myapplication.ui.navigation.Screen
import kotlinx.coroutines.launch

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun ReportList (navController: NavController?, viewModel: ReportViewModel = viewModel(factory = AppViewModelProvider.Factory))
{

    val context = LocalContext.current

    val coroutineScope = rememberCoroutineScope()
    val reportResultPageState = viewModel.reportResultPageUiState

    val startDateText = remember { mutableStateOf("") }
    val endDateText = remember { mutableStateOf("") }


    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 = stringResource(id = R.string.startDate),
                    textAlign = TextAlign.Center,
                )
                Spacer(modifier = Modifier.height(8.dp))
                BasicTextField(
                    value = startDateText.value,
                    onValueChange = { startDateText.value = 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),
                )
            }

            Column(
                modifier = Modifier
                    .width(180.dp) // Adjust the width as needed
                    .fillMaxHeight()
                    .padding(8.dp),
                horizontalAlignment = Alignment.CenterHorizontally,
                verticalArrangement = Arrangement.Center
            ) {
                Text(
                    text = stringResource(id = R.string.endDate),
                    textAlign = TextAlign.Center,
                )
                Spacer(modifier = Modifier.height(8.dp))
                BasicTextField(
                    value = endDateText.value,
                    onValueChange = { endDateText.value = 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(16.dp))

        Button(
            onClick = {
                coroutineScope.launch {
                    viewModel.onButtonClick(startDateText.value, endDateText.value)
                }
            },
            modifier = Modifier
                .fillMaxWidth()
                .padding(all = 10.dp)
                .border(4.dp, MaterialTheme.colorScheme.onPrimary, shape = RoundedCornerShape(10.dp)),
            shape = RoundedCornerShape(10.dp),
            colors = ButtonDefaults.buttonColors(containerColor = MaterialTheme.colorScheme.primary)
        ) {
            Text("Сформировать отчет")
        }

        viewModel.errorState?.let { errorMessage ->
            AlertDialog(
                onDismissRequest = { viewModel.errorState = null },
                title = { Text(text = "Ошибка") },
                text = { Text(errorMessage, color = MaterialTheme.colorScheme.onBackground) },
                buttons = {
                    Row(
                        modifier = Modifier
                            .fillMaxWidth()
                            .padding(8.dp),
                        horizontalArrangement = Arrangement.End
                    ) {
                        TextButton(onClick = { viewModel.errorState = null }) {
                            Text("Закрыть", color = MaterialTheme.colorScheme.onBackground)
                        }
                    }
                },
                modifier = Modifier.padding(16.dp),
                backgroundColor = MaterialTheme.colorScheme.background,
                contentColor = MaterialTheme.colorScheme.onBackground
            )
        }

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

        // Use AnimatedVisibility to animate the Card visibility
        AnimatedVisibility(visible = viewModel.cardVisible) {
            Card(
                border = BorderStroke(2.dp, MaterialTheme.colorScheme.onBackground),
                modifier = Modifier
                    .background(MaterialTheme.colorScheme.background)
                    .fillMaxWidth()
                    .padding(8.dp)
            ) {
                Column(
                    modifier = Modifier
                        .fillMaxSize()
                        .background(MaterialTheme.colorScheme.background)
                        .padding(8.dp),
                    verticalArrangement = Arrangement.Center,
                    horizontalAlignment = Alignment.CenterHorizontally
                ) {
                    Text(
                        text = "Результат",
                        textAlign = TextAlign.Center,
                        style = TextStyle(
                            color = MaterialTheme.colorScheme.onSurface,
                            fontSize = 24.sp
                        )
                    )

                    TableScreen(reportData = reportResultPageState.resReport)

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

                    if (viewModel.reportPageUiState.isEntryValid) {
                        Button(
                            onClick = {
                                coroutineScope.launch {
                                    viewModel.generatePdfFile(
                                        context = context,
                                        fileName = "Отчет по велосипедам",
                                        reportData = reportResultPageState.resReport
                                    )
                                }
                            },
                            modifier = Modifier
                                .fillMaxWidth()
                                .padding(all = 10.dp)
                                .border(4.dp, MaterialTheme.colorScheme.onPrimary, shape = RoundedCornerShape(10.dp)),
                            shape = RoundedCornerShape(10.dp),
                            colors = ButtonDefaults.buttonColors(containerColor = MaterialTheme.colorScheme.primary)
                        ) {
                            Text("Сформировать отчет PDF")
                        }
                    }
                }
            }
        }

        Button(
            onClick = {
                coroutineScope.launch {
                    navController?.navigate(Screen.BikeList.route)
                }
            },
            modifier = Modifier
                .fillMaxWidth()
                .padding(all = 10.dp)
                .border(4.dp, MaterialTheme.colorScheme.onPrimary, shape = RoundedCornerShape(10.dp)),
            shape = RoundedCornerShape(10.dp),
            colors = ButtonDefaults.buttonColors(containerColor = MaterialTheme.colorScheme.primary)
        ) {
            Text("Выйти")
        }
    }
}

@Composable
fun TableScreen(reportData: List<ReportRemote>) {

    Column(
        Modifier
            .padding(8.dp)
    ) {

        Row(
            modifier = Modifier
                .background(MaterialTheme.colorScheme.onBackground)
                .height(48.dp)
                .padding(4.dp)
                .fillMaxWidth(), // Занимаем максимальную ширину
            verticalAlignment = Alignment.CenterVertically // Выравниваем по центру вертикали
        ) {
            Text("ID", Modifier.weight(0.3f), color = MaterialTheme.colorScheme.background)
            Text("Дата", Modifier.weight(0.8f), color = MaterialTheme.colorScheme.background)
            Text("Вес", Modifier.weight(0.7f), color = MaterialTheme.colorScheme.background)
            Text("R", Modifier.weight(0.6f), color = MaterialTheme.colorScheme.background)
            Text("Цвет", Modifier.weight(1.0f), color = MaterialTheme.colorScheme.background)
            Text("Кол-во", Modifier.weight(0.5f), color = MaterialTheme.colorScheme.background)
            Text("Имя", Modifier.weight(1.0f), color = MaterialTheme.colorScheme.background)
        }

        // Here are all the lines of your table.
        reportData.forEach {
            val (id, dateTime, weight, radius,colorbike, maxCount, bikeName) = it
            Card(
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(vertical = 8.dp, horizontal = 4.dp),
            ) {
                Row(Modifier
                    .fillMaxWidth()
                    .background(MaterialTheme.colorScheme.background)) {
                    Text(id.toString(), Modifier.weight(0.3f))
                    Text(dateTime.toString(), Modifier.weight(0.8f))
                    Text(weight.toString(), Modifier.weight(0.7f))
                    Text(radius.toString(), Modifier.weight(0.6f))
                    Text(colorbike.toString(), Modifier.weight(1.0f))
                    Text(maxCount.toString(), Modifier.weight(0.5f))
                    Text(bikeName.toString(), Modifier.weight(1.0f))
                }
            }
        }
    }
}


