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

import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material3.Button
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.ui.Alignment
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.AdminDashboardDto
import com.runicgateway.app.ui.UiState
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.SectionLabel
import com.runicgateway.app.ui.components.StatusPill

/**
 * The staff dashboard (PLAN.md §1, M10): site mode + a site-mode toggle (admins
 * only), summary counts, and recent admin activity. Read-only for moderators/editors;
 * only [isAdmin] callers see the maintenance switch, and the server enforces it too.
 */
@Composable
fun AdminDashboardScreen(
    isAdmin: Boolean,
    modifier: Modifier = Modifier,
    viewModel: AdminDashboardViewModel = hiltViewModel(),
) {
    val state by viewModel.state.collectAsStateWithLifecycle()

    when (val ds = state.dashboard) {
        is UiState.Loading -> LoadingView(modifier)
        is UiState.Error -> ErrorView(ds.kind, onRetry = viewModel::load, modifier = modifier)
        is UiState.Success -> DashboardContent(
            data = ds.data,
            isAdmin = isAdmin,
            switching = state.switching,
            feedbackRes = state.feedback?.messageRes,
            onSetMode = viewModel::setSiteMode,
            modifier = modifier,
        )
    }
}

@Composable
private fun DashboardContent(
    data: AdminDashboardDto,
    isAdmin: Boolean,
    switching: Boolean,
    feedbackRes: Int?,
    onSetMode: (String) -> Unit,
    modifier: Modifier = Modifier,
) {
    val live = data.siteMode.equals("live", ignoreCase = true)
    Column(
        modifier = modifier
            .fillMaxSize()
            .verticalScroll(rememberScrollState())
            .padding(20.dp),
    ) {
        // ── Site status ──────────────────────────────────────────────
        SectionLabel(stringResource(R.string.admin_dashboard_site))
        Spacer(Modifier.height(8.dp))
        Row(verticalAlignment = Alignment.CenterVertically) {
            StatusPill(
                text = if (live) stringResource(R.string.admin_site_live) else stringResource(R.string.admin_site_maintenance),
                tone = if (live) PillTone.Success else PillTone.Warning,
            )
            data.lastChange.by?.takeIf { it.isNotBlank() }?.let { by ->
                Spacer(Modifier.width(12.dp))
                Text(
                    text = stringResource(R.string.admin_site_changed_by, by),
                    style = MaterialTheme.typography.bodySmall,
                    color = MaterialTheme.colorScheme.onSurfaceVariant,
                )
            }
        }

        if (isAdmin) {
            Spacer(Modifier.height(12.dp))
            Button(
                onClick = { onSetMode(if (live) "maintenance" else "live") },
                enabled = !switching,
                modifier = Modifier.fillMaxWidth(),
            ) {
                if (switching) {
                    CircularProgressIndicator(strokeWidth = 2.dp, modifier = Modifier.height(20.dp))
                } else {
                    Text(
                        stringResource(
                            if (live) R.string.admin_site_switch_maintenance else R.string.admin_site_switch_live,
                        ),
                    )
                }
            }
        }

        feedbackRes?.let {
            Spacer(Modifier.height(8.dp))
            Text(
                text = stringResource(it),
                style = MaterialTheme.typography.bodySmall,
                color = MaterialTheme.colorScheme.onSurfaceVariant,
            )
        }

        // ── Counts ───────────────────────────────────────────────────
        Spacer(Modifier.height(24.dp))
        SectionLabel(stringResource(R.string.admin_dashboard_counts))
        Spacer(Modifier.height(8.dp))
        StatRow(stringResource(R.string.admin_count_users), data.counts.users.toString())
        val totalPosts = data.counts.posts.values.sum()
        StatRow(stringResource(R.string.admin_count_posts), totalPosts.toString())
        data.counts.posts.forEach { (category, count) ->
            StatRow("· $category", count.toString())
        }

        // ── Recent activity ──────────────────────────────────────────
        if (data.recentActivity.isNotEmpty()) {
            Spacer(Modifier.height(24.dp))
            SectionLabel(stringResource(R.string.admin_dashboard_recent_activity))
            Spacer(Modifier.height(8.dp))
            data.recentActivity.forEach { row ->
                Column(Modifier.fillMaxWidth().padding(vertical = 6.dp)) {
                    Text(row.action, style = MaterialTheme.typography.bodyMedium)
                    val meta = listOfNotNull(row.username, row.createdAt).joinToString(" · ")
                    if (meta.isNotBlank()) {
                        Text(
                            text = meta,
                            style = MaterialTheme.typography.bodySmall,
                            color = MaterialTheme.colorScheme.onSurfaceVariant,
                        )
                    }
                }
            }
        }
    }
}

@Composable
private fun StatRow(label: String, value: String) {
    Row(
        modifier = Modifier.fillMaxWidth().padding(vertical = 4.dp),
        horizontalArrangement = Arrangement.SpaceBetween,
    ) {
        Text(label, style = MaterialTheme.typography.bodyMedium)
        Text(value, style = MaterialTheme.typography.bodyMedium, color = MaterialTheme.colorScheme.onSurfaceVariant)
    }
}
