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

import android.icu.util.Calendar
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.diegocayo.organizame.data.local.entity.TaskStatus
import com.diegocayo.organizame.domain.model.Task
import com.diegocayo.organizame.domain.repository.TaskRepository
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 javax.inject.Inject

@HiltViewModel
class TasksListViewModel @Inject constructor(
    private val taskRepository: TaskRepository
) : ViewModel() {

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

    init {
        loadTasks()
    }

    fun onEvent(event: TasksListEvent) {
        when (event) {
            is TasksListEvent.LoadTasks -> loadTasks()
            is TasksListEvent.UpdateTaskStatus -> updateTaskStatus(event.taskId, event.completed)
            is TasksListEvent.DeleteTask -> deleteTask(event.task)
            is TasksListEvent.NavigateToCreateTask -> {} // Manejado por la UI
            is TasksListEvent.ChangeDate -> {
                _state.value = _state.value.copy(selectedDate = event.date)
                loadTasks()
            }

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

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

    private fun loadTasks() {
        viewModelScope.launch {
            _state.value = _state.value.copy(isLoading = true)

            taskRepository.getAllTasks()
                .onEach { tasks ->
                    val filteredTasks = filterTasksByDate(tasks, _state.value.selectedDate)
                    _state.value = _state.value.copy(
                        tasks = filteredTasks,
                        pendingTasks = filteredTasks.filter { it.status == TaskStatus.PENDING },
                        completedTasks = filteredTasks.filter { it.status == TaskStatus.COMPLETED },
                        isLoading = false
                    )
                }
                .catch { e ->
                    _state.value = _state.value.copy(
                        error = e.message,
                        isLoading = false
                    )
                }
                .launchIn(viewModelScope)
        }
    }

    private fun filterTasksByDate(tasks: List<Task>, date: Long): List<Task> {
        val calendar = Calendar.getInstance()
        calendar.timeInMillis = date
        calendar.set(Calendar.HOUR_OF_DAY, 0)
        calendar.set(Calendar.MINUTE, 0)
        calendar.set(Calendar.SECOND, 0)
        calendar.set(Calendar.MILLISECOND, 0)
        val startOfDay = calendar.timeInMillis

        calendar.add(Calendar.DAY_OF_MONTH, 1)
        val startOfNextDay = calendar.timeInMillis

        return tasks.filter { task ->
            task.scheduledDate in startOfDay until startOfNextDay
        }
    }

    private fun updateTaskStatus(taskId: Long, completed: Boolean) {
        viewModelScope.launch {
            try {
                val newStatus = if (completed) TaskStatus.COMPLETED else TaskStatus.PENDING
                taskRepository.updateTaskStatus(taskId, newStatus)
            } catch (e: Exception) {
                _state.value = _state.value.copy(error = e.message)
            }
        }
    }

    private fun deleteTask(task: Task) {
        viewModelScope.launch {
            try {
                taskRepository.deleteTask(task)
            } catch (e: Exception) {
                _state.value = _state.value.copy(error = e.message)
            }
        }
    }
} 