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

import android.net.Uri
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import dagger.hilt.android.lifecycle.HiltViewModel
import id.iiyh.inatrading.feature.auth.domain.repository.AuthRepository
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 EditProfileUiState(
    val isLoading: Boolean = false,
    val isSaving: Boolean = false,
    val isUploadingImage: Boolean = false,
    val errorMessage: String? = null,
    val infoMessage: String? = null,
    val name: String = "",
    val email: String = "",
    val phone: String = "",
    val imageUrl: String? = null,
    val imageId: String? = null,
)

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

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

    init {
        loadProfile()
    }

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

            authRepository.getBuyerProfile()
                .onSuccess { profile ->
                    _uiState.update {
                        it.copy(
                            isLoading = false,
                            errorMessage = null,
                            name = profile.name.orEmpty(),
                            email = profile.email.orEmpty(),
                            phone = profile.mobile.orEmpty(),
                            imageUrl = profile.imageId,
                            imageId = profile.imageId,
                        )
                    }
                }
                .onFailure { error ->
                    _uiState.update {
                        it.copy(
                            isLoading = false,
                            errorMessage = error.message ?: "Gagal memuat profil",
                        )
                    }
                }
        }
    }

    fun onNameChange(value: String) {
        _uiState.update { it.copy(name = value) }
    }

    fun onPhoneChange(value: String) {
        _uiState.update { it.copy(phone = value.filter(Char::isDigit)) }
    }

    fun uploadProfileImage(uri: Uri) {
        viewModelScope.launch {
            _uiState.update {
                it.copy(
                    imageUrl = uri.toString(),
                    isUploadingImage = true,
                    infoMessage = null,
                    errorMessage = null,
                )
            }

            authRepository.uploadFile(uri)
                .onSuccess { fileId ->
                    _uiState.update {
                        it.copy(
                            isUploadingImage = false,
                            imageId = fileId,
                            infoMessage = "Foto profil berhasil diunggah.",
                        )
                    }
                }
                .onFailure { error ->
                    _uiState.update {
                        it.copy(
                            isUploadingImage = false,
                            infoMessage = error.message ?: "Gagal mengunggah foto profil",
                        )
                    }
                }
        }
    }

    fun onSaveClick() {
        val state = _uiState.value
        if (state.name.isBlank()) {
            _uiState.update { it.copy(infoMessage = "Nama lengkap wajib diisi.") }
            return
        }
        if (state.phone.isBlank()) {
            _uiState.update { it.copy(infoMessage = "Nomor telepon wajib diisi.") }
            return
        }
        if (state.isUploadingImage) {
            _uiState.update { it.copy(infoMessage = "Tunggu hingga upload foto selesai.") }
            return
        }

        viewModelScope.launch {
            _uiState.update { it.copy(isSaving = true, errorMessage = null, infoMessage = null) }
            authRepository.updateBuyerProfile(
                name = state.name,
                mobile = state.phone,
                imageId = state.imageId,
                email = state.email,
            ).onSuccess {
                _uiState.update {
                    it.copy(
                        isSaving = false,
                        infoMessage = "Profil berhasil diperbarui.",
                    )
                }
            }.onFailure { error ->
                _uiState.update {
                    it.copy(
                        isSaving = false,
                        infoMessage = error.message ?: "Gagal menyimpan profil",
                    )
                }
            }
        }
    }

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