package com.anypreta.bountyboard.ui.admin

import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.outlined.History
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateMapOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import androidx.lifecycle.viewmodel.compose.viewModel
import com.anypreta.bountyboard.data.AppContainer
import com.anypreta.bountyboard.data.model.AuditEntry
import com.anypreta.bountyboard.di.LocalAppContainer
import com.anypreta.bountyboard.di.containerVMFactory
import com.anypreta.bountyboard.ui.components.BBButton
import com.anypreta.bountyboard.ui.components.BBButtonStyle
import com.anypreta.bountyboard.ui.components.BBCard
import com.anypreta.bountyboard.ui.components.EmptyState
import com.anypreta.bountyboard.ui.components.Hairline
import com.anypreta.bountyboard.ui.components.ScreenState
import com.anypreta.bountyboard.ui.components.SectionLabel
import com.anypreta.bountyboard.ui.theme.BB
import com.anypreta.bountyboard.ui.theme.SplineMono
import com.anypreta.bountyboard.ui.util.relativeTime
import kotlinx.coroutines.launch

class AdminAuditViewModel(private val container: AppContainer) : ViewModel() {

    var loading by mutableStateOf(true)
        private set
    var error by mutableStateOf<String?>(null)
        private set
    var entries by mutableStateOf<List<AuditEntry>>(emptyList())
        private set
    var nextCursor by mutableStateOf<String?>(null)
        private set
    var loadingMore by mutableStateOf(false)
        private set

    init {
        load()
    }

    fun load() {
        loading = true; error = null
        viewModelScope.launch {
            try {
                val r = container.repo.call { adminAuditLog() }
                entries = r.entries
                nextCursor = r.nextCursor
            } catch (e: Exception) {
                error = e.message
            } finally {
                loading = false
            }
        }
    }

    fun loadMore() {
        val cursor = nextCursor ?: return
        if (loadingMore) return
        loadingMore = true
        viewModelScope.launch {
            try {
                val r = container.repo.call { adminAuditLog(cursor = cursor) }
                entries = entries + r.entries
                nextCursor = r.nextCursor
            } catch (_: Exception) {
                // keep prior entries; surface nothing destructive
            } finally {
                loadingMore = false
            }
        }
    }
}

@Composable
fun AdminAuditScreen() {
    val container = LocalAppContainer.current
    val vm: AdminAuditViewModel = viewModel(factory = containerVMFactory(container) { AdminAuditViewModel(it) })

    ScreenState(loading = vm.loading, error = vm.error, onRetry = { vm.load() }) {
        if (vm.entries.isEmpty()) {
            EmptyState(
                title = "No audit entries",
                subtitle = "Administrative actions appear here.",
                icon = Icons.Outlined.History,
            )
        } else {
            val expanded = remember { mutableStateMapOf<String, Boolean>() }
            LazyColumn(
                contentPadding = PaddingValues(16.dp),
                verticalArrangement = Arrangement.spacedBy(12.dp),
            ) {
                items(vm.entries, key = { it.id }) { entry ->
                    AuditCard(
                        entry = entry,
                        expanded = expanded[entry.id] == true,
                        onToggle = { expanded[entry.id] = !(expanded[entry.id] ?: false) },
                    )
                }
                if (vm.nextCursor != null) {
                    item(key = "load_more") {
                        Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.Center) {
                            BBButton(
                                "Load more",
                                onClick = { vm.loadMore() },
                                style = BBButtonStyle.Default,
                                loading = vm.loadingMore,
                                small = true,
                            )
                        }
                    }
                }
            }
        }
    }
}

@Composable
private fun AuditCard(entry: AuditEntry, expanded: Boolean, onToggle: () -> Unit) {
    val p = BB.colors
    BBCard(modifier = Modifier.fillMaxWidth(), onClick = onToggle) {
        Column(verticalArrangement = Arrangement.spacedBy(6.dp)) {
            Text(entry.action, style = MaterialTheme.typography.titleSmall, color = p.text)
            Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp)) {
                SectionLabel(buildString {
                    append(entry.entity)
                    entry.entityId?.let { append(" · "); append(it) }
                })
            }
            Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceBetween) {
                Text(entry.actorId ?: "system", fontFamily = SplineMono, style = MaterialTheme.typography.labelSmall, color = p.muted)
                Text(relativeTime(entry.at), style = MaterialTheme.typography.labelSmall, color = p.muted)
            }
            if (expanded && !entry.diff.isNullOrEmpty()) {
                Hairline()
                Column(verticalArrangement = Arrangement.spacedBy(4.dp)) {
                    entry.diff!!.entries.forEach { (k, v) ->
                        Text(
                            "$k → ${v?.toString() ?: "null"}",
                            fontFamily = SplineMono,
                            style = MaterialTheme.typography.bodySmall,
                            color = p.text,
                        )
                    }
                }
            }
        }
    }
}
