package com.radiola.ui.lyrics

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.radiola.domain.repository.LyricsRepository
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.launch
import javax.inject.Inject

sealed interface LyricsState {
    data object Loading : LyricsState
    data object Instrumental : LyricsState
    data class Found(val plain: String) : LyricsState
    data object NotFound : LyricsState
    data object Error : LyricsState
}

@HiltViewModel
class LyricsViewModel @Inject constructor(
    private val repository: LyricsRepository
) : ViewModel() {

    private val _state = MutableStateFlow<LyricsState>(LyricsState.Loading)
    val state: StateFlow<LyricsState> = _state

    fun load(artist: String, song: String, durationSec: Int? = null) {
        viewModelScope.launch {
            _state.value = LyricsState.Loading
            try {
                val result = repository.fetchLyrics(artist, song, durationSec)
                _state.value = when {
                    result == null -> LyricsState.NotFound
                    result.instrumental -> LyricsState.Instrumental
                    !result.plain.isNullOrBlank() -> LyricsState.Found(result.plain)
                    else -> LyricsState.NotFound
                }
            } catch (_: Exception) {
                _state.value = LyricsState.Error
            }
        }
    }
}
