package com.fabledsword.minstrel.admin.ui

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.AssistChip
import androidx.compose.material3.Button
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.HorizontalDivider
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedButton
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import androidx.navigation.NavHostController
import com.fabledsword.minstrel.models.AdminQuarantineItemRef
import com.fabledsword.minstrel.nav.AdminQuarantine
import com.fabledsword.minstrel.shared.widgets.ShellContentWindowInsets
import com.fabledsword.minstrel.shared.widgets.EmptyState
import com.fabledsword.minstrel.shared.widgets.ErrorRetry
import com.fabledsword.minstrel.shared.widgets.LoadingCentered
import com.fabledsword.minstrel.shared.widgets.MinstrelTopAppBar
import com.fabledsword.minstrel.shared.widgets.PullToRefreshScaffold

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun AdminQuarantineScreen(
    navController: NavHostController,
    viewModel: AdminQuarantineViewModel = hiltViewModel(),
) {
    val state by viewModel.uiState.collectAsStateWithLifecycle()
    Scaffold(
        contentWindowInsets = ShellContentWindowInsets,
        modifier = Modifier.fillMaxSize(),
        topBar = {
            MinstrelTopAppBar(
                title = "Admin · Quarantine",
                navController = navController,
                currentRouteName = AdminQuarantine::class.qualifiedName,
                onBack = { navController.popBackStack() },
            )
        },
    ) { inner ->
        PullToRefreshScaffold(
            onRefresh = { viewModel.refresh().join() },
            modifier = Modifier.fillMaxSize().padding(inner),
        ) {
            when (val s = state) {
                AdminQuarantineUiState.Loading -> LoadingCentered()
                AdminQuarantineUiState.Empty -> EmptyState(
                    title = "Queue is empty",
                    body = "When users flag tracks as bad rips, wrong tags, or " +
                        "duplicates, their reports get aggregated and surfaced here.",
                )
                is AdminQuarantineUiState.Error -> ErrorRetry(
                    title = "Couldn't load queue",
                    message = s.message,
                    onRetry = { viewModel.refresh() },
                )
                is AdminQuarantineUiState.Success -> QueueList(
                    rows = s.rows,
                    onResolve = viewModel::resolve,
                    onDeleteFile = viewModel::deleteFile,
                    onDeleteViaLidarr = viewModel::deleteViaLidarr,
                )
            }
        }
    }
}

@Composable
private fun QueueList(
    rows: List<AdminQuarantineItemRef>,
    onResolve: (String) -> Unit,
    onDeleteFile: (String) -> Unit,
    onDeleteViaLidarr: (String) -> Unit,
) {
    LazyColumn(modifier = Modifier.fillMaxSize()) {
        items(items = rows, key = { it.trackId }) { row ->
            QuarantineRow(
                row = row,
                onResolve = { onResolve(row.trackId) },
                onDeleteFile = { onDeleteFile(row.trackId) },
                onDeleteViaLidarr = { onDeleteViaLidarr(row.trackId) },
            )
            HorizontalDivider()
        }
    }
}

@Composable
private fun QuarantineRow(
    row: AdminQuarantineItemRef,
    onResolve: () -> Unit,
    onDeleteFile: () -> Unit,
    onDeleteViaLidarr: () -> Unit,
) {
    Column(
        modifier = Modifier
            .fillMaxWidth()
            .padding(horizontal = 16.dp, vertical = 12.dp),
        verticalArrangement = Arrangement.spacedBy(8.dp),
    ) {
        Text(
            text = row.trackTitle,
            style = MaterialTheme.typography.bodyLarge,
            color = MaterialTheme.colorScheme.onSurface,
            maxLines = 1,
            overflow = TextOverflow.Ellipsis,
        )
        Text(
            text = "${row.artistName} · ${row.albumTitle}",
            style = MaterialTheme.typography.bodySmall,
            color = MaterialTheme.colorScheme.onSurfaceVariant,
            maxLines = 1,
            overflow = TextOverflow.Ellipsis,
        )
        Row(horizontalArrangement = Arrangement.spacedBy(6.dp)) {
            AssistChip(
                onClick = {},
                enabled = false,
                label = {
                    Text(
                        text = "${row.reportCount} reports",
                        style = MaterialTheme.typography.labelSmall,
                    )
                },
            )
            if (row.topReasonSummary.isNotEmpty()) {
                AssistChip(
                    onClick = {},
                    enabled = false,
                    label = {
                        Text(
                            text = row.topReasonSummary,
                            style = MaterialTheme.typography.labelSmall,
                        )
                    },
                )
            }
        }
        ActionButtons(
            onResolve = onResolve,
            onDeleteFile = onDeleteFile,
            onDeleteViaLidarr = onDeleteViaLidarr,
        )
    }
}

@Composable
private fun ActionButtons(
    onResolve: () -> Unit,
    onDeleteFile: () -> Unit,
    onDeleteViaLidarr: () -> Unit,
) {
    Row(
        modifier = Modifier.fillMaxWidth(),
        horizontalArrangement = Arrangement.spacedBy(8.dp, Alignment.End),
    ) {
        TextButton(onClick = onResolve) { Text("Resolve") }
        OutlinedButton(onClick = onDeleteFile) { Text("Delete file") }
        Button(onClick = onDeleteViaLidarr) { Text("Delete + Lidarr") }
    }
}
