package com.pixelized.desktop.lwa.ui.screen.admin.character.edit.dialog

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.pixelized.desktop.lwa.repository.characterSheet.CharacterSheetRepository
import com.pixelized.desktop.lwa.ui.composable.error.ErrorSnackUio
import com.pixelized.desktop.lwa.utils.extention.unpack
import kotlinx.coroutines.flow.MutableSharedFlow
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.SharedFlow
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.update


class GMCharacterSheetCopyDialogViewModel(
    private val characterSheetRepository: CharacterSheetRepository,
    private val factory: GMCharacterSheetCopyDialogFactory,
) : ViewModel() {

    private val _dialog = MutableStateFlow<GMCharacterSheetCopyDialogUio?>(null)
    val dialog: StateFlow<GMCharacterSheetCopyDialogUio?> get() = _dialog

    private val _error = MutableSharedFlow<ErrorSnackUio>()
    val error: SharedFlow<ErrorSnackUio> get() = _error

    suspend fun showCharacterSheetCopyDialog(
        characterSheetId: String?,
        characterName: String?,
    ) {
        _dialog.value = factory.createDialogForm(
            scope = viewModelScope,
            characterSheetId = characterSheetId?.takeIf { it.isNotBlank() },
            characterName = characterName?.takeIf { it.isNotBlank() },
        )
    }

    suspend fun hideCharacterSheetCopyDialog() {
        _dialog.value = null
    }

    suspend fun isValid(): Boolean {
        try {
            val idFlow = _dialog.value?.id?.errorFlow as? MutableStateFlow<Boolean>
            val characterSheetId = _dialog.value?.id?.unpack<String>()

            if (characterSheetId == null) {
                idFlow?.update { true }
                error("Missing characterSheetId")
            }
            val isIdValid = characterSheetRepository.checkCharacterSheetIdValidity(
                characterSheetId = characterSheetId,
            )
            if (isIdValid.not()) {
                idFlow?.update { true }
                error("characterSheetId already in usage")
            }
            return isIdValid
        } catch (exception: Exception) {
            val message = ErrorSnackUio.from(exception)
            _error.emit(message)
            return false
        }
    }
}