package com.example.ops_android.ui.schedule

import androidx.lifecycle.ViewModel
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.viewModelScope
import com.example.ops_android.data.model.ScheduleEvent
import com.example.ops_android.data.repository.ScheduleRepository
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.launch
import java.text.SimpleDateFormat
import java.util.*

data class ScheduleUiState(
    val events: List<ScheduleEvent> = emptyList(),
    val currentYear: Int = Calendar.getInstance().get(Calendar.YEAR),
    val currentMonth: Int = Calendar.getInstance().get(Calendar.MONTH),
    val isLoading: Boolean = false,
    val errorMessage: String? = null,
    val showForm: Boolean = false,
    val editingEvent: ScheduleEvent? = null,
    val formTitle: String = "",
    val formDescription: String = "",
    val formDate: String = SimpleDateFormat("yyyy-MM-dd", Locale.US).format(Date()),
    val formStartTime: String = "",
    val formEndTime: String = "",
    val isSubmitting: Boolean = false
)

class ScheduleViewModel(
    private val repository: ScheduleRepository
) : ViewModel() {
    private val _uiState = MutableStateFlow(ScheduleUiState())
    val uiState: StateFlow<ScheduleUiState> = _uiState.asStateFlow()
    private val dateFormat = SimpleDateFormat("yyyy-MM-dd", Locale.US)

    init { loadEvents() }

    fun loadEvents() {
        val state = _uiState.value
        val cal = Calendar.getInstance()
        cal.set(state.currentYear, state.currentMonth, 1)
        val start = dateFormat.format(cal.time)
        cal.set(Calendar.DAY_OF_MONTH, cal.getActualMaximum(Calendar.DAY_OF_MONTH))
        val end = dateFormat.format(cal.time)

        viewModelScope.launch {
            _uiState.value = _uiState.value.copy(isLoading = true)
            repository.getEvents(start, end).fold(
                onSuccess = { _uiState.value = _uiState.value.copy(events = it, isLoading = false) },
                onFailure = { _uiState.value = _uiState.value.copy(isLoading = false, errorMessage = it.message) }
            )
        }
    }

    fun prevMonth() {
        val state = _uiState.value
        _uiState.value = state.copy(
            currentMonth = if (state.currentMonth == 0) { _uiState.value = _uiState.value.copy(currentYear = state.currentYear - 1); 11 } else state.currentMonth - 1
        )
        loadEvents()
    }

    fun nextMonth() {
        val state = _uiState.value
        _uiState.value = state.copy(
            currentMonth = if (state.currentMonth == 11) { _uiState.value = _uiState.value.copy(currentYear = state.currentYear + 1); 0 } else state.currentMonth + 1
        )
        loadEvents()
    }

    fun showAddForm(date: String) {
        _uiState.value = _uiState.value.copy(showForm = true, editingEvent = null, formTitle = "", formDescription = "", formDate = date, formStartTime = "", formEndTime = "")
    }

    fun showEditForm(event: ScheduleEvent) {
        _uiState.value = _uiState.value.copy(
            showForm = true, editingEvent = event,
            formTitle = event.title ?: "", formDescription = event.description ?: "",
            formDate = event.start_time?.take(10) ?: "", formStartTime = event.start_time?.substring(11)?.take(5) ?: "",
            formEndTime = event.end_time?.substring(11)?.take(5) ?: ""
        )
    }

    fun dismissForm() { _uiState.value = _uiState.value.copy(showForm = false) }
    fun onFormTitle(v: String) { _uiState.value = _uiState.value.copy(formTitle = v) }
    fun onFormDesc(v: String) { _uiState.value = _uiState.value.copy(formDescription = v) }
    fun onFormStartTime(v: String) { _uiState.value = _uiState.value.copy(formStartTime = v) }
    fun onFormEndTime(v: String) { _uiState.value = _uiState.value.copy(formEndTime = v) }

    fun submitForm() {
        val st = _uiState.value
        if (st.formTitle.isBlank()) { _uiState.value = st.copy(errorMessage = "标题不能为空"); return }
        val startTime = if (st.formStartTime.isNotBlank()) "${st.formDate}T${st.formStartTime}:00" else st.formDate
        val endTime = if (st.formEndTime.isNotBlank()) "${st.formDate}T${st.formEndTime}:00" else st.formDate
        val data = mapOf("title" to st.formTitle, "description" to st.formDescription, "start_time" to startTime, "end_time" to endTime)

        viewModelScope.launch {
            _uiState.value = _uiState.value.copy(isSubmitting = true)
            val r = if (st.editingEvent != null) repository.editEvent(data + ("id" to st.editingEvent.id)) else repository.addEvent(data)
            r.fold(onSuccess = { _uiState.value = _uiState.value.copy(showForm = false, isSubmitting = false); loadEvents() }, onFailure = { _uiState.value = _uiState.value.copy(isSubmitting = false, errorMessage = it.message) })
        }
    }

    fun deleteEvent(id: Int) {
        viewModelScope.launch { repository.deleteEvent(id).fold(onSuccess = { loadEvents() }, onFailure = { _uiState.value = _uiState.value.copy(errorMessage = it.message) }) }
    }

    class Factory(private val repo: ScheduleRepository) : ViewModelProvider.Factory {
        @Suppress("UNCHECKED_CAST") override fun <T : ViewModel> create(c: Class<T>): T = ScheduleViewModel(repo) as T
    }
}
