package com.pixelized.desktop.lwa.ui.composable.character.diminished

import androidx.compose.runtime.mutableStateOf
import androidx.compose.ui.text.TextRange
import androidx.compose.ui.text.input.TextFieldValue
import com.pixelized.desktop.lwa.repository.alteration.AlterationRepository
import com.pixelized.desktop.lwa.repository.characterSheet.CharacterSheetRepository
import com.pixelized.shared.lwa.model.AlteredCharacterSheetFactory
import com.pixelized.shared.lwa.model.characterSheet.CharacterSheet
import com.pixelized.shared.lwa.utils.signLabel
import lwacharactersheet.composeapp.generated.resources.Res
import lwacharactersheet.composeapp.generated.resources.character_sheet__diminished__label
import org.jetbrains.compose.resources.getString
import kotlin.math.abs

class CharacterSheetDiminishedDialogFactory(
    private val characterSheetRepository: CharacterSheetRepository,
    private val alterationRepository: AlterationRepository,
    private val alteredCharacterSheetFactory: AlteredCharacterSheetFactory,
) {
    suspend fun convertToDialogUio(
        characterSheetId: String?,
    ): CharacterSheetDiminishedDialogUio? {

        if (characterSheetId == null) return null

        val characterSheet: CharacterSheet? = characterSheetRepository.characterDetail(
            characterSheetId = characterSheetId,
        )

        if (characterSheet == null) return null

        val alteredCharacterSheet = alteredCharacterSheetFactory.sheet(
            characterSheet = characterSheet,
            alterations = alterationRepository.activeFieldAlterations(
                characterSheetId = characterSheetId
            ),
        )
        val textFieldValue = mutableStateOf(
            TextFieldValue(
                text = "${characterSheet.diminished}",
                selection = TextRange(index = 0),
            )
        )

        return CharacterSheetDiminishedDialogUio(
            characterSheetId = characterSheetId,
            label = getString(resource = Res.string.character_sheet__diminished__label),
            value = { textFieldValue.value },
            onValueChange = { value ->
                textFieldValue.value = when (value.text.toIntOrNull()?.takeIf { it >= 0 }) {
                    null -> TextFieldValue("0", selection = TextRange(index = 0))
                    else -> value
                }
            },
            additional = (alteredCharacterSheet.diminishedAlterations)
                .takeIf { it != 0 }
                ?.let { "${it.signLabel}${abs(it)}" }
        )
    }
}