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

import android.content.Context
import android.util.Log
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.example.myapplication.api.item.RestItemRepository
import com.example.myapplication.api.report.ReportRemote
import kotlinx.coroutines.launch
import java.text.ParseException
import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale

class ReportViewModel(private val itemRespository: RestItemRepository): ViewModel() {
    var reportPageUiState by mutableStateOf(ReportPageUiState())
        private set

    var reportResultPageUiState by mutableStateOf(ReportResultPageUiState())
        private set

    var cardVisible by mutableStateOf(false)
        private set

    var errorState by mutableStateOf<String?>(null)

    fun onUpdate(reportDetails: ReportDetails) {
        reportPageUiState = ReportPageUiState(reportDetails = reportDetails, isEntryValid = validateInput(reportDetails))
    }

    private fun validateInput(uiState: ReportDetails = reportPageUiState.reportDetails): Boolean {
        Log.d("validateInput", uiState.endDate.toString())
        return with(uiState) {
            startDate != Date(0) && endDate != Date(0) && startDate < endDate
        }
    }

    suspend fun getReport() {
        val dateFormatter = SimpleDateFormat("yyyy", Locale.getDefault())

        // Преобразование даты в строку в формате "yyyy"
        val startDateQueryParam = dateFormatter.format(reportPageUiState.reportDetails.startDate)
        val endDateQueryParam = dateFormatter.format(reportPageUiState.reportDetails.endDate)

        // Вызов репозитория с отформатированными датами
        val res = itemRespository.getReport(startDateQueryParam, endDateQueryParam)
        reportResultPageUiState = ReportResultPageUiState(res)
    }

    suspend fun generatePdfFile(context: Context, fileName: String, reportData: List<ReportRemote>) {
        itemRespository.createPdfFile(context, fileName, reportData)
    }

    fun onButtonClick(startDate: String, endDate: String) {
        viewModelScope.launch {
            val parsedStartDate = parseDate(startDate)
            val parsedEndDate = parseDate(endDate)

            if (validateDates(parsedStartDate, parsedEndDate)) {
                updateReportDetails(parsedStartDate, parsedEndDate)
                getReport()
                cardVisible = true
            } else {
                Log.d("Ошибка даты", "Неправильно указаны даты или года не являются 4-значными =${startDate}")
                errorState = "Ошибка фильтраций: неверно указаны даты"
            }
        }
    }

    private fun validateDates(startDate: Date?, endDate: Date?): Boolean {
        return startDate != null && endDate != null && startDate < endDate
    }

    private fun updateReportDetails(startDate: Date?, endDate: Date?) {
        if (startDate != null && endDate != null) {
            onUpdate(reportPageUiState.reportDetails.copy(startDate = startDate, endDate = endDate))
        }
    }

    private fun parseDate(dateString: String): Date? {
        return try {
            // Use SimpleDateFormat or any other method to parse the string into a Date object
            // For example:
            SimpleDateFormat("yyyy", Locale.getDefault()).parse(dateString)
        } catch (e: ParseException) {
            // Handle parsing error
            null
        }
    }

}

data class ReportDetails(
    val startDate: Date = Date(0),
    val endDate: Date = Date(0)
)

data class ReportPageUiState(
    val reportDetails: ReportDetails = ReportDetails(),
    val isEntryValid: Boolean = false
)

data class ReportResultPageUiState(
    var resReport: List<ReportRemote> = emptyList()
)
