package com.radiola.ui.alarms

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.radiola.data.local.dao.AlarmDao
import com.radiola.data.local.entity.AlarmEntity
import com.radiola.domain.model.Station
import com.radiola.domain.usecase.GetStationsUseCase
import com.radiola.service.AlarmScheduler
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.stateIn
import kotlinx.coroutines.launch
import javax.inject.Inject

@HiltViewModel
class AlarmsViewModel @Inject constructor(
    private val alarmDao: AlarmDao,
    private val alarmScheduler: AlarmScheduler,
    getStationsUseCase: GetStationsUseCase
) : ViewModel() {

    val alarms: StateFlow<List<AlarmEntity>> = alarmDao.getAll()
        .stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), emptyList())

    val stations: StateFlow<List<Station>> = getStationsUseCase()
        .stateIn(viewModelScope, SharingStarted.WhileSubscribed(5_000), emptyList())

    /** Добавить или обновить будильник; если включён — запланировать. */
    fun addOrUpdate(alarm: AlarmEntity) {
        viewModelScope.launch {
            val id = alarmDao.upsert(alarm).toInt()
            val saved = alarm.copy(id = if (alarm.id == 0) id else alarm.id)
            if (saved.enabled) alarmScheduler.schedule(saved)
            else alarmScheduler.cancel(saved.id)
        }
    }

    /** Переключить включён/выключен. */
    fun toggle(alarm: AlarmEntity) {
        viewModelScope.launch {
            val newEnabled = !alarm.enabled
            alarmDao.setEnabled(alarm.id, newEnabled)
            if (newEnabled) alarmScheduler.schedule(alarm.copy(enabled = true))
            else alarmScheduler.cancel(alarm.id)
        }
    }

    /** Удалить будильник и отменить планировщик. */
    fun delete(alarm: AlarmEntity) {
        viewModelScope.launch {
            alarmScheduler.cancel(alarm.id)
            alarmDao.delete(alarm.id)
        }
    }
}
