package com.approagency.pharmacy.presentation.viewModel


import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.approagency.pharmacy.domain.model.PharmacyDetail
import com.approagency.pharmacy.domain.model.PharmacyItem
import com.approagency.pharmacy.domain.usecase.GetPharmaciesUseCase
import com.approagency.pharmacy.domain.usecase.GetPharmacyDetailUseCase
import com.approagency.pharmacy.utils.toUserMessage
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.launch
sealed class PharmacyDetailState {
    object Idle : PharmacyDetailState()
    object Loading : PharmacyDetailState()
    data class Success(val detail: PharmacyDetail) : PharmacyDetailState()
    data class Error(val message: String) : PharmacyDetailState()
}
sealed class PharmacyState {
    object Idle : PharmacyState()
    object Loading : PharmacyState()
    data class Success(val items: List<PharmacyItem>) : PharmacyState()
    data class Error(val message: String) : PharmacyState()
}

class PharmacyViewModel(
    private val getPharmaciesUseCase: GetPharmaciesUseCase,
    private val getPharmacyDetailUseCase: GetPharmacyDetailUseCase
) : ViewModel() {

    private val _state = MutableStateFlow<PharmacyState>(PharmacyState.Idle)
    val state: StateFlow<PharmacyState> = _state.asStateFlow()


    // استفاده از Map برای نگهداری State هر داروخانه به صورت جداگانه
    private val _pharmacyDetailStates = MutableStateFlow<Map<String, PharmacyDetailState>>(emptyMap())
    val pharmacyDetailStates: StateFlow<Map<String, PharmacyDetailState>> = _pharmacyDetailStates.asStateFlow()

    private var currentGenericDrugId: String = ""
    private var currentBrandIrc: String = "0"
    private var currentProvinceId: String = "0"

    fun loadPharmacyDetail(pharmacyUrl: String) {
        // اگر در حال حاضر لود می‌شود یا موفقیت آمیز بوده، دوباره درخواست نده
        val currentState = _pharmacyDetailStates.value[pharmacyUrl]
        if (currentState is PharmacyDetailState.Loading || currentState is PharmacyDetailState.Success) {
            return
        }

        viewModelScope.launch {
            // تنظیم Loading برای این داروخانه خاص
            _pharmacyDetailStates.value = _pharmacyDetailStates.value.toMutableMap().apply {
                put(pharmacyUrl, PharmacyDetailState.Loading)
            }

            try {
                val detail = getPharmacyDetailUseCase(pharmacyUrl)
                _pharmacyDetailStates.value = _pharmacyDetailStates.value.toMutableMap().apply {
                    put(pharmacyUrl, PharmacyDetailState.Success(detail))
                }
            } catch (e: Exception) {
                _pharmacyDetailStates.value = _pharmacyDetailStates.value.toMutableMap().apply {
                    put(pharmacyUrl, PharmacyDetailState.Error(e.toUserMessage()))
                }
            }
        }
    }


    fun search(genericDrugId: String, brandIrc: String, provinceId: String) {
        currentGenericDrugId = genericDrugId
        currentBrandIrc = brandIrc
        currentProvinceId = provinceId

        // پاک کردن نتایج جستجوی قبلی تا داده‌ی قبلی نمایش داده نشود
        _pharmacyDetailStates.value = emptyMap()

        // حداقل یکی از شناسه‌ها (ژنریک یا برند) باید معتبر باشد
        val hasGeneric = genericDrugId.isNotBlank() && genericDrugId != "0"
        val hasBrand = brandIrc.isNotBlank() && brandIrc != "0"
        if (!hasGeneric && !hasBrand) {
            _state.value = PharmacyState.Error("شناسه دارو یافت نشد")
            return
        }

        viewModelScope.launch {
            _state.value = PharmacyState.Loading
            try {
                val result = getPharmaciesUseCase(genericDrugId, brandIrc, provinceId)
                _state.value = PharmacyState.Success(result)
            } catch (e: Exception) {
                _state.value = PharmacyState.Error(e.toUserMessage())
            }
        }
    }

    fun retry() {
        search(currentGenericDrugId, currentBrandIrc, currentProvinceId)
    }
}