package id.iiyh.inatrading.feature.favorite.presentation

import androidx.lifecycle.SavedStateHandle
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import dagger.hilt.android.lifecycle.HiltViewModel
import id.iiyh.inatrading.core.data.remote.SessionExpiredException
import id.iiyh.inatrading.feature.auth.domain.repository.AuthRepository
import id.iiyh.inatrading.feature.favorite.domain.FavoriteGroupProduct
import id.iiyh.inatrading.feature.favorite.domain.FavoriteRepository
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

data class FavoriteGroupDetailUiState(
    val groupId: String = "",
    val groupName: String = "",
    val items: List<FavoriteGroupProduct> = emptyList(),
    val isLoading: Boolean = false,
    val removingProductId: String? = null,
    val errorMessage: String? = null,
    val sessionExpired: Boolean = false,
)

@HiltViewModel
class FavoriteGroupDetailViewModel @Inject constructor(
    savedStateHandle: SavedStateHandle,
    private val favoriteRepository: FavoriteRepository,
    private val authRepository: AuthRepository,
) : ViewModel() {

    private val groupId: String = savedStateHandle.get<String>("groupId").orEmpty()
    private val groupName: String = savedStateHandle.get<String>("groupName").orEmpty()

    private val _uiState = MutableStateFlow(
        FavoriteGroupDetailUiState(
            groupId = groupId,
            groupName = groupName,
        )
    )
    val uiState: StateFlow<FavoriteGroupDetailUiState> = _uiState.asStateFlow()

    init {
        loadItems()
    }

    fun loadItems() {
        if (groupId.isBlank()) {
            _uiState.update {
                it.copy(
                    isLoading = false,
                    errorMessage = "Invalid favorite group",
                )
            }
            return
        }

        viewModelScope.launch {
            _uiState.update {
                it.copy(
                    isLoading = true,
                    errorMessage = null,
                    sessionExpired = false,
                )
            }

            favoriteRepository.getFavoriteGroupItems(groupId)
                .onSuccess { items ->
                    _uiState.update {
                        it.copy(
                            items = items,
                            isLoading = false,
                            removingProductId = null,
                            errorMessage = null,
                            sessionExpired = false,
                        )
                    }
                }
                .onFailure { handleFailure(it, fallbackMessage = "Failed to load favorite items") }
        }
    }

    fun removeFavorite(productId: String) {
        viewModelScope.launch {
            _uiState.update {
                it.copy(
                    removingProductId = productId,
                    errorMessage = null,
                    sessionExpired = false,
                )
            }

            favoriteRepository.removeProductFromFavorite(productId)
                .onSuccess {
                    _uiState.update { state ->
                        state.copy(
                            items = state.items.filterNot { item -> item.productId == productId },
                            removingProductId = null,
                            errorMessage = null,
                            sessionExpired = false,
                        )
                    }
                }
                .onFailure { handleFailure(it, fallbackMessage = "Failed to remove favorite item") }
        }
    }

    fun consumeError() {
        _uiState.update { it.copy(errorMessage = null) }
    }

    fun consumeSessionExpired() {
        _uiState.update { it.copy(sessionExpired = false) }
    }

    private suspend fun handleFailure(error: Throwable, fallbackMessage: String) {
        if (error is SessionExpiredException) {
            authRepository.logout()
            _uiState.update {
                it.copy(
                    isLoading = false,
                    removingProductId = null,
                    errorMessage = null,
                    sessionExpired = true,
                )
            }
            return
        }

        _uiState.update {
            it.copy(
                isLoading = false,
                removingProductId = null,
                errorMessage = error.message ?: fallbackMessage,
                sessionExpired = false,
            )
        }
    }
}
