package com.diegocayo.organizame.presentation.features.main.events.list

import android.icu.util.Calendar
import android.util.Log
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.diegocayo.organizame.domain.model.Event
import com.diegocayo.organizame.domain.repository.EventRepository
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.catch
import kotlinx.coroutines.flow.launchIn
import kotlinx.coroutines.flow.onEach
import kotlinx.coroutines.launch
import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale
import javax.inject.Inject

@HiltViewModel
class EventsListViewModel @Inject constructor(
    private val eventRepository: EventRepository
) : ViewModel() {

    private val _state = MutableStateFlow(EventsListState())
    val state: StateFlow<EventsListState> = _state.asStateFlow()
    private val dateFormat = SimpleDateFormat("dd/MM/yyyy", Locale("es", "ES"))

    init {
        loadEvents()
    }

    fun onEvent(event: EventsListEvent) {
        when (event) {
            is EventsListEvent.LoadEvents -> loadEvents()
            is EventsListEvent.DeleteEvent -> deleteEvent(event.event)
            is EventsListEvent.NavigateToCreateEvent -> {} // Manejado por la UI
            is EventsListEvent.ChangeDate -> {
                _state.value = _state.value.copy(selectedDate = event.date)
                loadEvents()
            }

            is EventsListEvent.NextDay -> {
                val calendar = Calendar.getInstance().apply {
                    timeInMillis = _state.value.selectedDate
                    add(Calendar.DAY_OF_MONTH, 1)
                }
                _state.value = _state.value.copy(selectedDate = calendar.timeInMillis)
                loadEvents()
            }

            is EventsListEvent.PreviousDay -> {
                val calendar = Calendar.getInstance().apply {
                    timeInMillis = _state.value.selectedDate
                    add(Calendar.DAY_OF_MONTH, -1)
                }
                _state.value = _state.value.copy(selectedDate = calendar.timeInMillis)
                loadEvents()
            }
        }
    }

    private fun loadEvents() {
        viewModelScope.launch {
            _state.value = _state.value.copy(isLoading = true)
            Log.d(
                "EventsListViewModel",
                "Cargando eventos para la fecha: ${dateFormat.format(Date(_state.value.selectedDate))}"
            )

            eventRepository.getEventsByDate(_state.value.selectedDate)
                .onEach { events ->
                    Log.d("EventsListViewModel", "Eventos cargados: ${events.size}")
                    events.forEach { event ->
                        Log.d(
                            "EventsListViewModel",
                            "Evento: ${event.title} - Fecha: ${dateFormat.format(Date(event.date))}"
                        )
                    }
                    _state.value = _state.value.copy(
                        events = events,
                        isLoading = false
                    )
                }
                .catch { e ->
                    Log.e("EventsListViewModel", "Error al cargar eventos", e)
                    _state.value = _state.value.copy(
                        error = e.message,
                        isLoading = false
                    )
                }
                .launchIn(viewModelScope)
        }
    }

    private fun deleteEvent(event: Event) {
        viewModelScope.launch {
            try {
                eventRepository.deleteEvent(event)
            } catch (e: Exception) {
                Log.e("EventsListViewModel", "Error al eliminar evento", e)
                _state.value = _state.value.copy(error = e.message)
            }
        }
    }
} 