package theorycrafter.ui.settings

import androidx.compose.foundation.layout.*
import androidx.compose.material.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import compose.utils.VSpacer
import compose.widgets.DropdownField
import theorycrafter.CompositionExportTemplatesSettings
import theorycrafter.TheorycrafterContext
import theorycrafter.TheorycrafterContext.settings
import theorycrafter.tournaments.TournamentDescriptor
import theorycrafter.tournaments.TournamentDescriptorById
import theorycrafter.ui.TextField
import theorycrafter.ui.TheorycrafterTheme
import theorycrafter.ui.widgets.CheckboxedText


/**
 * The tournament settings pane.
 */
@Composable
fun TournamentSettingsPane() {
    Column(
        horizontalAlignment = Alignment.Start,
        verticalArrangement = Arrangement.spacedBy(TheorycrafterTheme.spacing.xxlarge),
        modifier = Modifier
            .padding(TheorycrafterTheme.spacing.edgeMargins)
    ) {
        val activeTournamentDescriptor = TheorycrafterContext.tournaments.activeTournamentDescriptor

        ActiveTournamentSection(activeTournamentDescriptor)
        CheckboxedText(
            text = "Tag new fits with the active tournament" +
                if (activeTournamentDescriptor == null) "" else " (e.g. #${activeTournamentDescriptor.suggestedFitTag})",
            enabled = activeTournamentDescriptor != null,
            state = settings.suggestTournamentFitTagForNewFits
        )
        CompositonExportTemplatesSection()
    }
}


/**
 * The section for selecting the active tournament.
 */
@Composable
private fun ActiveTournamentSection(activeTournamentDescriptor: TournamentDescriptor?) {
    val tournamentDescriptors: List<TournamentDescriptor?> = remember {
        buildList {
            add(null)
            addAll(TournamentDescriptorById.values)
        }
    }
    Column {
        Text("Active Tournament", style = TheorycrafterTheme.textStyles.mediumHeading)
        VSpacer(TheorycrafterTheme.spacing.xsmall)
        DropdownField(
            items = tournamentDescriptors,
            selectedItem = activeTournamentDescriptor,
            itemToString = { it?.name ?: "None" },
            modifier = Modifier.width(200.dp),
            onItemSelected = { _, descriptor ->
                settings.activeTournamentId = descriptor?.id
            }
        )

        VSpacer(TheorycrafterTheme.spacing.small)

        Text(
            text = "Active tournament will affect the following:",
            style = TheorycrafterTheme.textStyles.detailedText()
        )
        VSpacer(TheorycrafterTheme.spacing.xxxsmall)
        Text(
            text = """
                • Only tournament-legal ships will appear in the "New Fit" dialog.
                • Only tournament-legal items (e.g. modules) will be suggested for completion in the fit editor.
                • Illegal items, or combinations of items that are illegal, will be highlighted in red in the fit editor.
                • Tournament-appropriate charges (e.g. ammo) will be auto-loaded into new modules.
                • "Pack Cargohold for Battle" dialog will not suggest tournament-inappropriate items.  
            """.trimIndent(),
            style = TheorycrafterTheme.textStyles.detailedText()
        )
    }
}


/**
 * The section for specifying the templates for composition export.
 */
@Composable
private fun CompositonExportTemplatesSection() {
    Column {
        Text("Composition Export Templates", style = TheorycrafterTheme.textStyles.mediumHeading)
        VSpacer(TheorycrafterTheme.spacing.larger)
        CompositionExportTemplateSettingEditor(
            label = "Title Template",
            replacementTokens = listOf(
                "compName" to "Composition name"
            ),
            template = CompositionExportTemplatesSettings::titleTemplate,
            templatesWithUpdatedTemplate = { templates, newValue -> templates.copy(titleTemplate = newValue) }
        )
        CompositionExportTemplateSettingEditor(
            label = "Ship Template",
            replacementTokens = listOf(
                "shipCount" to "Number of identical ships in the composition",
                "shipName" to "Ship name",
                "shipShortName" to "Short ship name",
                "fitName" to "Name of the associated fit",
                "eftFit(sections)" to
                        "EFT export of the associated fit, where 'sections' specifies which sections to include via a " +
                        "comma-separated list of 'charges', 'implants', 'boosters', 'cargo' and 'mutations'",
            ),
            template = CompositionExportTemplatesSettings::shipTemplate,
            templatesWithUpdatedTemplate = { templates, newValue -> templates.copy(shipTemplate = newValue) }
        )
        CompositionExportTemplateSettingEditor(
            label = "Utility Template",
            replacementTokens = listOf(
                "utilityCount" to "Number of utilities of the corresponding kind",
                "utilityName" to "Utility name",
                "utilitySummary" to "Utility summary",
            ),
            template = CompositionExportTemplatesSettings::utilityTemplate,
            templatesWithUpdatedTemplate = { templates, newValue -> templates.copy(utilityTemplate = newValue) }
        )
        CompositionExportTemplateSettingEditor(
            label = "Notes Template",
            replacementTokens = listOf(
                "note" to "Composition note",
                "plainShipList" to "Plain list of ships"
            ),
            template = CompositionExportTemplatesSettings::noteTemplate,
            templatesWithUpdatedTemplate = { templates, newValue -> templates.copy(noteTemplate = newValue) }
        )
    }
}


/**
 * The editor for a composition export template.
 */
@Composable
private fun CompositionExportTemplateSettingEditor(
    label: String,
    replacementTokens: List<Pair<String, String>>,
    template: (CompositionExportTemplatesSettings) -> String,
    templatesWithUpdatedTemplate: (CompositionExportTemplatesSettings, String) -> CompositionExportTemplatesSettings
) {
    val templateValue = template(settings.compositionExportTemplates)
    TheorycrafterTheme.TextField(
        value = templateValue,
        onValueChange = {
            settings.compositionExportTemplates = templatesWithUpdatedTemplate(settings.compositionExportTemplates, it)
        },
        minLines = 2,
        label = { Text(label) },
        modifier = Modifier.fillMaxWidth()
    )
    VSpacer(TheorycrafterTheme.spacing.xxxsmall)
    Text(
        style = TheorycrafterTheme.textStyles.detailedText(),
        text = replacementTokens.joinToString(separator = "\n") { (token, description) ->
            $$"• $$${token}$: $$description"
        }
    )
    VSpacer(TheorycrafterTheme.spacing.larger)
}
