package com.example.elva.ui.calendar

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.example.elva.data.models.health.Period
import com.example.elva.data.repository.HealthRepository
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.launch
import java.time.LocalDate
import java.time.YearMonth
import javax.inject.Inject

@HiltViewModel
class CalendarViewModel @Inject constructor(
    private val healthRepository: HealthRepository
) : ViewModel() {

    private val _state = MutableStateFlow(CalendarState())
    val state: StateFlow<CalendarState> = _state.asStateFlow()

    init {
        loadCalendarData()
    }

    private fun loadCalendarData() {
        viewModelScope.launch {
            try {
                val cycleInfo = healthRepository.getCycleInfo()
                val periods = healthRepository.getPeriods()

                _state.value = CalendarState(
                    currentMonth = YearMonth.now(),
                    periods = periods,
                    cycleInfo = cycleInfo,
                    isLoading = false
                )
            } catch (e: Exception) {
                _state.value = _state.value.copy(
                    error = e.message,
                    isLoading = false
                )
            }
        }
    }

    fun previousMonth() {
        _state.value = _state.value.copy(
            currentMonth = _state.value.currentMonth.minusMonths(1)
        )
    }

    fun nextMonth() {
        _state.value = _state.value.copy(
            currentMonth = _state.value.currentMonth.plusMonths(1)
        )
    }

    fun selectDate(date: LocalDate) {
        _state.value = _state.value.copy(selectedDate = date)
    }

    fun showEditPeriodDialog(startDate: LocalDate? = null) {
        _state.value = _state.value.copy(
            showEditDialog = true,
            editingPeriod = startDate?.let { date ->
                // Попытка найти существующий период
                _state.value.periods.find {
                    !date.isBefore(it.startDate) && (it.endDate == null || !date.isAfter(it.endDate))
                }
            }
        )
    }

    fun dismissEditDialog() {
        _state.value = _state.value.copy(
            showEditDialog = false,
            editingPeriod = null
        )
    }

    fun savePeriod(period: Period) {
        viewModelScope.launch {
            try {
                if (period.id == 0L) {
                    healthRepository.addPeriod(period)
                } else {
                    healthRepository.updatePeriod(period)
                }
                dismissEditDialog()
                loadCalendarData()
            } catch (e: Exception) {
                _state.value = _state.value.copy(error = e.message)
            }
        }
    }

    fun deletePeriod(periodId: Long) {
        viewModelScope.launch {
            try {
                healthRepository.deletePeriod(periodId)
                loadCalendarData()
            } catch (e: Exception) {
                _state.value = _state.value.copy(error = e.message)
            }
        }
    }
}

data class CalendarState(
    val currentMonth: YearMonth = YearMonth.now(),
    val selectedDate: LocalDate? = null,
    val periods: List<Period> = emptyList(),
    val cycleInfo: com.example.elva.data.models.health.CycleInfo? = null,
    val showEditDialog: Boolean = false,
    val editingPeriod: Period? = null,
    val isLoading: Boolean = true,
    val error: String? = null
)

