package com.horrortv.app.presentation.home

import android.util.Log
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.horrortv.app.domain.model.AppError
import com.horrortv.app.domain.model.MovieCategory
import com.horrortv.app.domain.repository.MovieRepository
import com.horrortv.app.util.ApiException
import dagger.hilt.android.lifecycle.HiltViewModel
import kotlinx.coroutines.Job
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch
import javax.inject.Inject

@HiltViewModel
class HomeViewModel @Inject constructor(
    private val repository: MovieRepository
) : ViewModel() {

    private companion object {
        const val TAG = "HomeViewModel"
    }

    private val _uiState = MutableStateFlow(HomeUiState())
    val uiState: StateFlow<HomeUiState> = _uiState.asStateFlow()

    private var loadJob: Job? = null

    init {
        loadFeaturedCategories()
    }

    fun loadFeaturedCategories() {
        loadJob?.cancel()
        loadJob = viewModelScope.launch {
            Log.d(TAG, "Loading featured categories")
            _uiState.update { it.copy(isLoading = true, error = null) }

            try {
                val categories = repository.getFeaturedCategories()
                Log.d(TAG, "Loaded ${categories.size} categories")
                _uiState.update { it.copy(categories = categories, isLoading = false) }
            } catch (e: Exception) {
                Log.e(TAG, "Error loading categories", e)
                val appError = if (e is ApiException) {
                    e.toAppError()
                } else {
                    AppError.UnknownError(
                        userMessage = "Error inesperado. Intenta de nuevo.",
                        debugMessage = "Unhandled exception: ${e.message}",
                        cause = e
                    )
                }
                _uiState.update { it.copy(isLoading = false, error = appError) }
            }
        }
    }

    fun retry() {
        loadFeaturedCategories()
    }

    fun clearError() {
        _uiState.update { it.copy(error = null) }
    }
}

data class HomeUiState(
    val categories: List<MovieCategory> = emptyList(),
    val isLoading: Boolean = false,
    val error: AppError? = null
)