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

import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
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.foundation.lazy.items
import androidx.compose.material3.HorizontalDivider
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
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.GovernorDto
import com.runicgateway.app.data.api.dto.GovernorTermDto
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.ShardCard

/** The town-governor board (PLAN.md §6.2), live via `city.update`, with per-city history. */
@Composable
fun GovernorsScreen(
    modifier: Modifier = Modifier,
    viewModel: GovernorsViewModel = hiltViewModel(),
) {
    val state by viewModel.state.collectAsStateWithLifecycle()
    val connected by viewModel.connected.collectAsStateWithLifecycle()
    val history by viewModel.history.collectAsStateWithLifecycle()

    Column(modifier = modifier.fillMaxSize()) {
        Row(
            Modifier.fillMaxWidth().padding(horizontal = 16.dp, vertical = 10.dp),
            horizontalArrangement = Arrangement.End,
        ) {
            LiveChip(connected)
        }
        when (val s = state) {
            is UiState.Loading -> LoadingView()
            is UiState.Error -> ErrorView(s.kind, onRetry = viewModel::load)
            is UiState.Success -> {
                if (s.data.isEmpty()) {
                    EmptyView(stringResource(R.string.governors_empty))
                } else {
                    LazyColumn(
                        modifier = Modifier.fillMaxSize().padding(horizontal = 16.dp),
                        verticalArrangement = Arrangement.spacedBy(8.dp),
                        contentPadding = androidx.compose.foundation.layout.PaddingValues(bottom = 16.dp),
                    ) {
                        items(s.data, key = { it.city }) { city ->
                            CityCard(
                                city = city,
                                terms = history[city.city],
                                onExpand = { viewModel.loadHistory(city.city) },
                            )
                        }
                    }
                }
            }
        }
    }
}

@Composable
private fun CityCard(
    city: GovernorDto,
    terms: List<GovernorTermDto>?,
    onExpand: () -> Unit,
) {
    var expanded by remember { mutableStateOf(false) }
    ShardCard(Modifier.fillMaxWidth()) {
        Column {
            Column(
                Modifier
                    .fillMaxWidth()
                    .clickable {
                        expanded = !expanded
                        if (expanded) onExpand()
                    }
                    .padding(16.dp),
            ) {
                Text(city.city, style = MaterialTheme.typography.titleMedium)
                Text(
                    text = city.governor?.label?.let { stringResource(R.string.governor_current, it) }
                        ?: stringResource(R.string.governor_none),
                    style = MaterialTheme.typography.bodyMedium,
                    color = MaterialTheme.colorScheme.onSurfaceVariant,
                    modifier = Modifier.padding(top = 4.dp),
                )
                city.electionPhase?.takeIf { it.isNotBlank() && !it.equals("none", ignoreCase = true) }?.let {
                    Text(
                        text = stringResource(R.string.governor_election, it),
                        style = MaterialTheme.typography.labelSmall,
                        color = MaterialTheme.colorScheme.primary,
                        modifier = Modifier.padding(top = 2.dp),
                    )
                }
            }
            if (expanded) {
                HorizontalDivider()
                Column(Modifier.padding(16.dp)) {
                    Text(
                        stringResource(R.string.governor_history),
                        style = MaterialTheme.typography.titleSmall,
                    )
                    when {
                        terms == null -> Text(
                            stringResource(R.string.governor_history_loading),
                            style = MaterialTheme.typography.bodySmall,
                            color = MaterialTheme.colorScheme.onSurfaceVariant,
                            modifier = Modifier.padding(top = 6.dp),
                        )
                        terms.isEmpty() -> Text(
                            stringResource(R.string.governor_history_empty),
                            style = MaterialTheme.typography.bodySmall,
                            color = MaterialTheme.colorScheme.onSurfaceVariant,
                            modifier = Modifier.padding(top = 6.dp),
                        )
                        else -> terms.forEach { term ->
                            Text(
                                text = term.governor?.label ?: stringResource(R.string.governor_none),
                                style = MaterialTheme.typography.bodySmall,
                                modifier = Modifier.padding(top = 6.dp),
                            )
                        }
                    }
                }
            }
        }
    }
}
