package dev.ulfrx.recipe.ui.components.calendar

import androidx.compose.runtime.Immutable
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.update
import kotlinx.datetime.DatePeriod
import kotlinx.datetime.LocalDate
import kotlinx.datetime.plus

@Immutable
data class HorizonCalendarState(
    val selectedDate: LocalDate,
    val isCalendarOpen: Boolean = false,
)

/**
 * Shared state holder for "pick a horizon date" screens (Pantry, Shopping).
 * Owns the date + open flag and enforces "no past dates" on selection. Lives
 * inside the owning ViewModel as a plain field — not a ViewModel itself.
 *
 * [today] is parameterised so tests can pin the clock.
 */
class HorizonCalendarHolder(
    initialDate: LocalDate = defaultHorizon(),
    private val today: () -> LocalDate = ::todayInSystemTz,
) {
    private val _state = MutableStateFlow(HorizonCalendarState(selectedDate = initialDate))
    val state: StateFlow<HorizonCalendarState> = _state.asStateFlow()

    fun setOpen(open: Boolean) {
        _state.update { it.copy(isCalendarOpen = open) }
    }

    fun close() = setOpen(false)

    fun select(date: LocalDate) {
        if (date < today()) return
        _state.update { it.copy(selectedDate = date, isCalendarOpen = false) }
    }

    companion object {
        private const val DEFAULT_HORIZON_DAYS = 7

        fun defaultHorizon(today: LocalDate = todayInSystemTz()): LocalDate = today.plus(DatePeriod(days = DEFAULT_HORIZON_DAYS - 1))
    }
}
