/*
 * SPDX-License-Identifier: GPL-3.0-or-later
 */
package com.runicgateway.app.ui.shard

import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.ExperimentalLayoutApi
import androidx.compose.foundation.layout.FlowRow
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.res.stringResource
import androidx.compose.ui.unit.dp
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import com.runicgateway.app.R
import com.runicgateway.app.data.api.dto.RulesetCapsDto
import com.runicgateway.app.data.api.dto.RulesetDto
import com.runicgateway.app.ui.UiState
import com.runicgateway.app.ui.components.EmptyView
import com.runicgateway.app.ui.components.ErrorView
import com.runicgateway.app.ui.components.LoadingView
import com.runicgateway.app.ui.components.PillTone
import com.runicgateway.app.ui.components.ShardCard
import com.runicgateway.app.ui.components.StatusPill

/**
 * The shard ruleset (PLAN.md §9 M11): what this world is configured to do.
 *
 * Every block renders only when the shard published it — an omitted block means the
 * system is off, not that the value is unknown, so an empty section would assert
 * something false.
 */
@Composable
fun RulesScreen(
    modifier: Modifier = Modifier,
    viewModel: RulesViewModel = hiltViewModel(),
) {
    val state by viewModel.state.collectAsStateWithLifecycle()

    when (val s = state) {
        is UiState.Loading -> LoadingView(modifier)
        is UiState.Error -> ErrorView(s.kind, onRetry = viewModel::load, modifier = modifier)
        is UiState.Success -> {
            val ruleset = s.data
            // A null body is a successful read of a shard that has never published its
            // ruleset — distinct from the feature being switched off, which is an error
            // state above.
            if (ruleset == null) {
                EmptyView(stringResource(R.string.rules_unpublished), modifier)
            } else {
                RulesetContent(ruleset, modifier)
            }
        }
    }
}

@Composable
private fun RulesetContent(ruleset: RulesetDto, modifier: Modifier = Modifier) {
    LazyColumn(
        modifier = modifier.fillMaxSize().padding(horizontal = 16.dp),
        verticalArrangement = Arrangement.spacedBy(12.dp),
        contentPadding = androidx.compose.foundation.layout.PaddingValues(vertical = 16.dp),
    ) {
        item {
            RuleCard(stringResource(R.string.rules_section_shard)) {
                RuleRow(stringResource(R.string.rules_name), ruleset.shard)
                RuleRow(stringResource(R.string.rules_expansion), ruleset.expansion)
                // `connect` is the ruleset's one admin-configurable field: an operator
                // who published an address may still want it behind a login, so its
                // absence here is a setting, not a missing value.
                RuleRow(stringResource(R.string.rules_connect), ruleset.connect)
            }
        }
        if (ruleset.systems.isNotEmpty()) {
            item { SystemsCard(ruleset.systems) }
        }
        ruleset.caps?.let { caps -> item { CapsCard(caps) } }
        item {
            val accounts = ruleset.accounts
            val housing = ruleset.housing
            if (accounts != null || housing != null) {
                RuleCard(stringResource(R.string.rules_section_accounts)) {
                    RuleRow(stringResource(R.string.rules_char_slots), accounts?.charSlots?.toString())
                    RuleRow(stringResource(R.string.rules_per_ip), accounts?.perIp?.toString())
                    RuleRow(
                        stringResource(R.string.rules_house_limit),
                        housing?.accountHouseLimit?.toString(),
                    )
                }
            }
        }
        ruleset.vendors?.let { vendors ->
            item {
                RuleCard(stringResource(R.string.rules_section_vendors)) {
                    RuleRow(
                        stringResource(R.string.rules_restock_delay),
                        vendors.restockDelayMinutes?.let { stringResource(R.string.rules_minutes, it) },
                    )
                    RuleRow(stringResource(R.string.rules_max_sell), vendors.maxSell?.toString())
                }
            }
        }
        ruleset.schedule?.let { schedule ->
            item {
                RuleCard(stringResource(R.string.rules_section_schedule)) {
                    RuleRow(
                        stringResource(R.string.rules_autosave),
                        schedule.autoSaveFrequencyMinutes?.let { stringResource(R.string.rules_minutes, it) },
                    )
                    RuleRow(
                        stringResource(R.string.rules_autorestart),
                        formatRestart(
                            schedule.autoRestartEnabled,
                            schedule.autoRestartHour,
                            schedule.autoRestartMinute,
                        ),
                    )
                }
            }
        }
    }
}

@OptIn(ExperimentalLayoutApi::class)
@Composable
private fun SystemsCard(systems: Map<String, Boolean>) {
    RuleCard(stringResource(R.string.rules_section_systems)) {
        FlowRow(
            Modifier.padding(top = 6.dp),
            horizontalArrangement = Arrangement.spacedBy(6.dp),
            verticalArrangement = Arrangement.spacedBy(6.dp),
        ) {
            // Sorted so the list is stable across reloads; the wire order is a config
            // read order and carries no meaning.
            systems.entries.sortedBy { it.key }.forEach { (key, on) ->
                StatusPill(
                    text = humaniseSystem(key),
                    tone = if (on) PillTone.Success else PillTone.Neutral,
                )
            }
        }
    }
}

@Composable
private fun CapsCard(caps: RulesetCapsDto) {
    RuleCard(stringResource(R.string.rules_section_caps)) {
        // Skill caps arrive in TENTHS (1000 = 100.0). Showing the raw number would read
        // as a shard with ten times the usual limit.
        RuleRow(stringResource(R.string.rules_skill_cap), caps.skillCap?.let { formatSkillCap(it) })
        RuleRow(stringResource(R.string.rules_total_skill_cap), caps.totalSkillCap?.let { formatSkillCap(it) })
        RuleRow(stringResource(R.string.rules_stat_cap), caps.stat?.toString())
        RuleRow(stringResource(R.string.rules_str_cap), caps.str?.toString())
        RuleRow(stringResource(R.string.rules_dex_cap), caps.dex?.toString())
        RuleRow(stringResource(R.string.rules_int_cap), caps.int?.toString())
    }
}

@Composable
private fun RuleCard(title: String, content: @Composable () -> Unit) {
    ShardCard(Modifier.fillMaxWidth()) {
        Column(Modifier.padding(16.dp)) {
            Text(title, style = MaterialTheme.typography.titleMedium)
            content()
        }
    }
}

/** One label/value line. Renders nothing when the shard published no value. */
@Composable
private fun RuleRow(label: String, value: String?) {
    if (value.isNullOrBlank()) return
    Row(
        Modifier.fillMaxWidth().padding(top = 6.dp),
        horizontalArrangement = Arrangement.SpaceBetween,
    ) {
        Text(label, style = MaterialTheme.typography.bodyMedium, color = MaterialTheme.colorScheme.onSurfaceVariant)
        Text(value, style = MaterialTheme.typography.bodyMedium)
    }
}

// ── Pure helpers (unit-tested) ───────────────────────────────────────────────

/** `cityLoyalty` → "City loyalty". The systems block is a flat bag of config keys. */
internal fun humaniseSystem(key: String): String = key
    .replace(Regex("([a-z0-9])([A-Z])"), "$1 $2")
    .replaceFirstChar { it.uppercaseChar() }

/** A skill cap already converted out of tenths: drop the ".0" on whole values. */
internal fun formatSkillCap(value: Double): String =
    if (value % 1.0 == 0.0) value.toInt().toString() else "%.1f".format(value)

/** The auto-restart schedule, or null when the shard doesn't run one. */
internal fun formatRestart(enabled: Boolean?, hour: Int?, minute: Int?): String? {
    if (enabled != true) return null
    if (hour == null) return null
    return "%02d:%02d".format(hour, minute ?: 0)
}
