package id.iiyh.inatrading.feature.profile.presentation

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import dagger.hilt.android.lifecycle.HiltViewModel
import id.iiyh.inatrading.feature.auth.domain.repository.AuthRepository
import id.iiyh.inatrading.feature.profile.data.model.ShippingAddress
import javax.inject.Inject
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.asStateFlow
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch

data class ShippingAddressesUiState(
    val isLoading: Boolean = false,
    val addresses: List<ShippingAddress> = emptyList(),
    val errorMessage: String? = null,
    val infoMessage: String? = null,
)

@HiltViewModel
class ShippingAddressesViewModel @Inject constructor(
    private val authRepository: AuthRepository,
) : ViewModel() {

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

    init {
        loadAddresses()
    }

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

            authRepository.getAddresses()
                .onSuccess { addresses ->
                    _uiState.update {
                        it.copy(
                            isLoading = false,
                            addresses = addresses,
                            errorMessage = null,
                        )
                    }
                }
                .onFailure { error ->
                    _uiState.update {
                        it.copy(
                            isLoading = false,
                            errorMessage = error.message ?: "Gagal memuat alamat pengiriman",
                        )
                    }
                }
        }
    }

    fun onAddAddressClick() {
        _uiState.update {
            it.copy(infoMessage = "Fitur tambah alamat akan segera tersedia.")
        }
    }

    fun consumeInfoMessage() {
        _uiState.update { it.copy(infoMessage = null) }
    }
}
