/*
 * 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.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.Checkbox
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
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.SupportPageDto
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 support (help-page) queue (PLAN.md §1, M10): open tickets with reply/close,
 * over `/admin/shard/pages…` (admin/moderator). Empty when there are no open pages
 * (or the shard is offline); every read/write degrades cleanly (§7).
 */
@Composable
fun AdminSupportScreen(
    modifier: Modifier = Modifier,
    viewModel: AdminSupportViewModel = hiltViewModel(),
) {
    val state by viewModel.state.collectAsStateWithLifecycle()
    var replyTo by remember { mutableStateOf<SupportPageDto?>(null) }

    Column(modifier.fillMaxSize()) {
        state.feedback?.let {
            Text(
                text = stringResource(it.messageRes),
                style = MaterialTheme.typography.bodySmall,
                color = if (it.ok) MaterialTheme.colorScheme.onSurfaceVariant else MaterialTheme.colorScheme.error,
                modifier = Modifier.fillMaxWidth().padding(horizontal = 16.dp, vertical = 6.dp),
            )
        }
        when (val s = state.pages) {
            is UiState.Loading -> LoadingView()
            is UiState.Error -> ErrorView(s.kind, onRetry = viewModel::load)
            is UiState.Success ->
                if (s.data.isEmpty()) {
                    EmptyView(stringResource(R.string.admin_support_empty))
                } else {
                    LazyColumn(Modifier.fillMaxSize().padding(16.dp)) {
                        items(s.data, key = { it.pageId }) { page ->
                            SupportPageCard(
                                page = page,
                                busy = state.busy,
                                onReply = { replyTo = page },
                                onClose = { viewModel.close(page.pageId) },
                            )
                        }
                    }
                }
        }
    }

    replyTo?.let { page ->
        RespondDialog(
            onDismiss = { replyTo = null },
            onSend = { message, close ->
                viewModel.respond(page.pageId, message, close)
                replyTo = null
            },
        )
    }
}

@Composable
private fun SupportPageCard(
    page: SupportPageDto,
    busy: Boolean,
    onReply: () -> Unit,
    onClose: () -> Unit,
) {
    ShardCard(Modifier.fillMaxWidth().padding(vertical = 6.dp)) {
        Column(Modifier.padding(12.dp)) {
            val who = page.sender?.name ?: page.sender?.account ?: page.pageId
            Text(
                text = listOfNotNull(page.type, who).joinToString(" · "),
                style = MaterialTheme.typography.bodyLarge,
            )
            page.message?.takeIf { it.isNotBlank() }?.let {
                Spacer(Modifier.height(4.dp))
                Text(it, style = MaterialTheme.typography.bodyMedium, color = MaterialTheme.colorScheme.onSurfaceVariant)
            }
            Row(Modifier.fillMaxWidth().padding(top = 8.dp), horizontalArrangement = Arrangement.End) {
                TextButton(onClick = onReply, enabled = !busy) { Text(stringResource(R.string.admin_support_reply)) }
                TextButton(onClick = onClose, enabled = !busy) { Text(stringResource(R.string.admin_support_close)) }
            }
        }
    }
}

@Composable
private fun RespondDialog(
    onDismiss: () -> Unit,
    onSend: (message: String, close: Boolean) -> Unit,
) {
    var message by rememberSaveable { mutableStateOf("") }
    var alsoClose by rememberSaveable { mutableStateOf(true) }

    AlertDialog(
        onDismissRequest = onDismiss,
        confirmButton = { TextButton(onClick = { onSend(message, alsoClose) }) { Text(stringResource(R.string.admin_support_send)) } },
        dismissButton = { TextButton(onClick = onDismiss) { Text(stringResource(R.string.action_cancel)) } },
        title = { Text(stringResource(R.string.admin_support_reply)) },
        text = {
            Column {
                OutlinedTextField(value = message, onValueChange = { message = it }, label = { Text(stringResource(R.string.admin_support_message)) }, modifier = Modifier.fillMaxWidth())
                Row(Modifier.fillMaxWidth().padding(top = 8.dp), verticalAlignment = Alignment.CenterVertically) {
                    Checkbox(checked = alsoClose, onCheckedChange = { alsoClose = it })
                    Text(stringResource(R.string.admin_support_close_after))
                }
            }
        },
    )
}
