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

import com.pixelized.desktop.lwa.ui.composable.textfield.LwaTextFieldFlow
import com.pixelized.desktop.lwa.ui.composable.textfield.createLwaTextField
import com.pixelized.desktop.lwa.ui.composable.textfield.createLwaTextFieldFlow
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.StateFlow
import kotlinx.coroutines.flow.combine
import kotlinx.coroutines.flow.stateIn
import lwacharactersheet.composeapp.generated.resources.Res
import lwacharactersheet.composeapp.generated.resources.character_sheet_edit__id_label
import lwacharactersheet.composeapp.generated.resources.character_sheet_edit__name_label
import org.jetbrains.compose.resources.getString

class GMCharacterSheetCopyDialogFactory {

    suspend fun createDialogForm(
        scope: CoroutineScope,
        characterSheetId: String?,
        characterName: String?,
    ): GMCharacterSheetCopyDialogUio {
        val idFlow = createLwaTextFieldFlow(
            label = getString(Res.string.character_sheet_edit__id_label),
            value = characterSheetId ?: "",
        )
        val nameFlow = createLwaTextFieldFlow(
            label = getString(Res.string.character_sheet_edit__name_label),
            value = characterName?.let { "$it (copy)" } ?: "",
        )
        return GMCharacterSheetCopyDialogUio(
            id = idFlow.createLwaTextField(
                checkForError = { it.isBlank() },
            ),
            name = nameFlow.createLwaTextField(
                checkForError = { it.isBlank() },
            ),
            enableConfirm = enableConfirm(
                scope = scope,
                idFlow = idFlow,
                nameFlow = nameFlow,
            ),
        )
    }

    private fun enableConfirm(
        scope: CoroutineScope,
        idFlow: LwaTextFieldFlow,
        nameFlow: LwaTextFieldFlow,
    ): StateFlow<Boolean> {
        return combine(
            idFlow.valueFlow,
            idFlow.errorFlow,
            nameFlow.valueFlow,
            nameFlow.errorFlow,
            transform = ::enableConfirm
        ).stateIn(
            scope = scope,
            started = SharingStarted.Lazily,
            initialValue = enableConfirm(
                id = idFlow.valueFlow.value,
                idError = idFlow.errorFlow.value,
                name = idFlow.valueFlow.value,
                nameError = nameFlow.errorFlow.value,
            )
        )
    }

    fun enableConfirm(
        id: String,
        idError: Boolean,
        name: String,
        nameError: Boolean,
    ): Boolean {
        return idError.not() && nameError.not() && id.isNotBlank() && name.isNotBlank()
    }
}