/*
 * 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.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.FilterChip
import androidx.compose.material3.HorizontalDivider
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedButton
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Switch
import androidx.compose.material3.Tab
import androidx.compose.material3.TabRow
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableIntStateOf
import androidx.compose.runtime.mutableStateOf
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.AdminPostDto
import com.runicgateway.app.data.api.dto.AdminWikiCategoryDto
import com.runicgateway.app.data.api.dto.AdminWikiTagDto
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.ShardCard
import com.runicgateway.app.ui.components.StatusPill

/**
 * The staff content screen (PLAN.md §1, M10): news posts and wiki taxonomy, in two
 * tabs. Create/publish/delete over the existing `/admin/posts` + `/admin/wiki/…`
 * routes; the CMS block/hero editor stays out of scope. Any staff role; the server
 * re-checks on every call.
 */
@Composable
fun AdminContentScreen(
    modifier: Modifier = Modifier,
    viewModel: AdminContentViewModel = hiltViewModel(),
) {
    val state by viewModel.state.collectAsStateWithLifecycle()
    var tab by rememberSaveable { mutableIntStateOf(0) }
    var showNewPost by rememberSaveable { mutableStateOf(false) }
    var showNewCategory by rememberSaveable { mutableStateOf(false) }

    Column(modifier.fillMaxSize()) {
        TabRow(selectedTabIndex = tab) {
            Tab(selected = tab == 0, onClick = { tab = 0 }, text = { Text(stringResource(R.string.admin_content_tab_posts)) })
            Tab(selected = tab == 1, onClick = { tab = 1 }, text = { Text(stringResource(R.string.admin_content_tab_wiki)) })
        }

        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 (tab) {
            0 -> PostsTab(
                state = state.posts,
                busy = state.busy,
                onNew = { showNewPost = true },
                onToggle = viewModel::togglePublish,
                onDelete = viewModel::deletePost,
                onRetry = viewModel::loadPosts,
            )
            else -> WikiTab(
                state = state.categories,
                tags = state.tags,
                busy = state.busy,
                onNew = { showNewCategory = true },
                onDelete = viewModel::deleteCategory,
                onRetry = viewModel::loadWiki,
            )
        }
    }

    if (showNewPost) {
        NewPostDialog(
            categories = viewModel.postCategories,
            onDismiss = { showNewPost = false },
            onCreate = { cat, title, excerpt, body, published ->
                viewModel.createPost(cat, title, excerpt, body, published)
                showNewPost = false
            },
        )
    }
    if (showNewCategory) {
        NewCategoryDialog(
            onDismiss = { showNewCategory = false },
            onCreate = { slug, title, desc, sort ->
                viewModel.createCategory(slug, title, desc, sort)
                showNewCategory = false
            },
        )
    }
}

@Composable
private fun PostsTab(
    state: UiState<List<AdminPostDto>>,
    busy: Boolean,
    onNew: () -> Unit,
    onToggle: (AdminPostDto) -> Unit,
    onDelete: (Long) -> Unit,
    onRetry: () -> Unit,
) {
    when (state) {
        is UiState.Loading -> LoadingView()
        is UiState.Error -> ErrorView(state.kind, onRetry = onRetry)
        is UiState.Success -> LazyColumn(Modifier.fillMaxSize().padding(16.dp)) {
            item {
                OutlinedButton(onClick = onNew, enabled = !busy, modifier = Modifier.fillMaxWidth().padding(bottom = 8.dp)) {
                    Text(stringResource(R.string.admin_content_new_post))
                }
            }
            items(state.data, key = { it.id }) { post ->
                ShardCard(Modifier.fillMaxWidth().padding(vertical = 6.dp)) {
                    Column(Modifier.padding(12.dp)) {
                        Text(post.title, style = MaterialTheme.typography.bodyLarge)
                        Spacer(Modifier.height(4.dp))
                        Row(verticalAlignment = Alignment.CenterVertically) {
                            StatusPill(
                                text = if (post.isPublished) stringResource(R.string.admin_content_published)
                                else stringResource(R.string.admin_content_draft),
                                tone = if (post.isPublished) PillTone.Success else PillTone.Neutral,
                            )
                            Spacer(Modifier.width(8.dp))
                            Text(post.category, style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant)
                        }
                        Row(Modifier.fillMaxWidth().padding(top = 8.dp), horizontalArrangement = Arrangement.End) {
                            TextButton(onClick = { onToggle(post) }, enabled = !busy) {
                                Text(
                                    stringResource(
                                        if (post.isPublished) R.string.admin_content_unpublish else R.string.admin_content_publish,
                                    ),
                                )
                            }
                            TextButton(onClick = { onDelete(post.id) }, enabled = !busy) {
                                Text(stringResource(R.string.admin_content_delete), color = MaterialTheme.colorScheme.error)
                            }
                        }
                    }
                }
            }
        }
    }
}

@Composable
private fun WikiTab(
    state: UiState<List<AdminWikiCategoryDto>>,
    tags: List<AdminWikiTagDto>,
    busy: Boolean,
    onNew: () -> Unit,
    onDelete: (Long) -> Unit,
    onRetry: () -> Unit,
) {
    when (state) {
        is UiState.Loading -> LoadingView()
        is UiState.Error -> ErrorView(state.kind, onRetry = onRetry)
        is UiState.Success -> LazyColumn(Modifier.fillMaxSize().padding(16.dp)) {
            item {
                OutlinedButton(onClick = onNew, enabled = !busy, modifier = Modifier.fillMaxWidth().padding(bottom = 8.dp)) {
                    Text(stringResource(R.string.admin_content_new_category))
                }
            }
            items(state.data, key = { it.id }) { cat ->
                ShardCard(Modifier.fillMaxWidth().padding(vertical = 6.dp)) {
                    Column(Modifier.padding(12.dp)) {
                        Text(cat.title, style = MaterialTheme.typography.bodyLarge)
                        Text(
                            text = stringResource(R.string.admin_content_cat_meta, cat.slug, cat.pageCount ?: 0),
                            style = MaterialTheme.typography.bodySmall,
                            color = MaterialTheme.colorScheme.onSurfaceVariant,
                        )
                        Row(Modifier.fillMaxWidth().padding(top = 8.dp), horizontalArrangement = Arrangement.End) {
                            TextButton(onClick = { onDelete(cat.id) }, enabled = !busy) {
                                Text(stringResource(R.string.admin_content_delete), color = MaterialTheme.colorScheme.error)
                            }
                        }
                    }
                }
            }
            if (tags.isNotEmpty()) {
                item {
                    HorizontalDivider(Modifier.padding(vertical = 12.dp))
                    Text(
                        stringResource(R.string.admin_content_tags, tags.joinToString(", ") { it.label }),
                        style = MaterialTheme.typography.bodySmall,
                        color = MaterialTheme.colorScheme.onSurfaceVariant,
                    )
                }
            }
        }
    }
}

@Composable
private fun NewPostDialog(
    categories: List<String>,
    onDismiss: () -> Unit,
    onCreate: (category: String, title: String, excerpt: String, body: String, published: Boolean) -> Unit,
) {
    var category by rememberSaveable { mutableStateOf(categories.first()) }
    var title by rememberSaveable { mutableStateOf("") }
    var excerpt by rememberSaveable { mutableStateOf("") }
    var body by rememberSaveable { mutableStateOf("") }
    var published by rememberSaveable { mutableStateOf(false) }

    AlertDialog(
        onDismissRequest = onDismiss,
        confirmButton = {
            TextButton(onClick = { onCreate(category, title, excerpt, body, published) }) {
                Text(stringResource(R.string.admin_content_create))
            }
        },
        dismissButton = { TextButton(onClick = onDismiss) { Text(stringResource(R.string.action_cancel)) } },
        title = { Text(stringResource(R.string.admin_content_new_post)) },
        text = {
            Column {
                Row(horizontalArrangement = Arrangement.spacedBy(6.dp)) {
                    categories.forEach { c ->
                        FilterChip(selected = category == c, onClick = { category = c }, label = { Text(c) })
                    }
                }
                OutlinedTextField(value = title, onValueChange = { title = it }, singleLine = true, label = { Text(stringResource(R.string.admin_content_field_title)) }, modifier = Modifier.fillMaxWidth().padding(top = 8.dp))
                OutlinedTextField(value = excerpt, onValueChange = { excerpt = it }, label = { Text(stringResource(R.string.admin_content_field_excerpt)) }, modifier = Modifier.fillMaxWidth().padding(top = 8.dp))
                OutlinedTextField(value = body, onValueChange = { body = it }, label = { Text(stringResource(R.string.admin_content_field_body)) }, modifier = Modifier.fillMaxWidth().padding(top = 8.dp))
                Row(Modifier.fillMaxWidth().padding(top = 8.dp), verticalAlignment = Alignment.CenterVertically) {
                    Text(stringResource(R.string.admin_content_publish_now), modifier = Modifier.weight(1f))
                    Switch(checked = published, onCheckedChange = { published = it })
                }
            }
        },
    )
}

@Composable
private fun NewCategoryDialog(
    onDismiss: () -> Unit,
    onCreate: (slug: String, title: String, description: String, sortOrder: Int?) -> Unit,
) {
    var slug by rememberSaveable { mutableStateOf("") }
    var title by rememberSaveable { mutableStateOf("") }
    var description by rememberSaveable { mutableStateOf("") }
    var sort by rememberSaveable { mutableStateOf("") }

    AlertDialog(
        onDismissRequest = onDismiss,
        confirmButton = {
            TextButton(onClick = { onCreate(slug, title, description, sort.toIntOrNull()) }) {
                Text(stringResource(R.string.admin_content_create))
            }
        },
        dismissButton = { TextButton(onClick = onDismiss) { Text(stringResource(R.string.action_cancel)) } },
        title = { Text(stringResource(R.string.admin_content_new_category)) },
        text = {
            Column {
                OutlinedTextField(value = slug, onValueChange = { slug = it }, singleLine = true, label = { Text(stringResource(R.string.admin_content_field_slug)) }, modifier = Modifier.fillMaxWidth())
                OutlinedTextField(value = title, onValueChange = { title = it }, singleLine = true, label = { Text(stringResource(R.string.admin_content_field_title)) }, modifier = Modifier.fillMaxWidth().padding(top = 8.dp))
                OutlinedTextField(value = description, onValueChange = { description = it }, label = { Text(stringResource(R.string.admin_content_field_description)) }, modifier = Modifier.fillMaxWidth().padding(top = 8.dp))
                OutlinedTextField(value = sort, onValueChange = { sort = it.filter(Char::isDigit) }, singleLine = true, label = { Text(stringResource(R.string.admin_content_field_sort)) }, modifier = Modifier.fillMaxWidth().padding(top = 8.dp))
            }
        },
    )
}
