package com.anypreta.bountyboard.ui.admin

import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.ExperimentalLayoutApi
import androidx.compose.foundation.layout.FlowRow
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.outlined.Add
import androidx.compose.material.icons.outlined.Business
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
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.draw.clip
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.Customer
import com.anypreta.bountyboard.di.LocalAppContainer
import com.anypreta.bountyboard.di.containerVMFactory
import com.anypreta.bountyboard.ui.components.BBBadge
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.ConfirmDialog
import com.anypreta.bountyboard.ui.components.EmptyState
import com.anypreta.bountyboard.ui.components.FilterPill
import com.anypreta.bountyboard.ui.components.MessageBox
import com.anypreta.bountyboard.ui.components.MessageKind
import com.anypreta.bountyboard.ui.components.ScreenState
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 AdminCustomersViewModel(private val container: AppContainer) : ViewModel() {

    var loading by mutableStateOf(true)
        private set
    var error by mutableStateOf<String?>(null)
        private set
    var customers by mutableStateOf<List<Customer>>(emptyList())
        private set
    var actionError by mutableStateOf<String?>(null)
        private set
    var actionInfo by mutableStateOf<String?>(null)
        private set

    var includeArchived by mutableStateOf(false)
        private set

    init {
        load()
    }

    fun toggleArchived() {
        includeArchived = !includeArchived; load()
    }

    fun load() {
        loading = true; error = null
        viewModelScope.launch {
            try {
                val r = container.repo.call { adminCustomers(includeArchived = if (includeArchived) true else null) }
                customers = r.customers
            } catch (e: Exception) {
                error = e.message
            } finally {
                loading = false
            }
        }
    }

    fun syncNow(id: String) {
        actionError = null; actionInfo = null
        viewModelScope.launch {
            try {
                container.repo.action { adminSyncNow(id) }
                actionInfo = "Sync queued"
            } catch (e: Exception) {
                actionError = e.message
            }
        }
    }

    fun delete(id: String) {
        actionError = null; actionInfo = null
        viewModelScope.launch {
            try {
                container.repo.action { adminDeleteCustomer(id) }
                load()
            } catch (e: Exception) {
                actionError = e.message
            }
        }
    }
}

@OptIn(ExperimentalLayoutApi::class)
@Composable
fun AdminCustomersScreen(onEditCustomer: (String) -> Unit) {
    val container = LocalAppContainer.current
    val vm: AdminCustomersViewModel = viewModel(factory = containerVMFactory(container) { AdminCustomersViewModel(it) })
    val p = BB.colors

    var deleteFor by remember { mutableStateOf<Customer?>(null) }

    Column(Modifier.fillMaxWidth()) {
        Row(
            Modifier.fillMaxWidth().padding(horizontal = 16.dp, vertical = 12.dp),
            verticalAlignment = Alignment.CenterVertically,
            horizontalArrangement = Arrangement.spacedBy(8.dp),
        ) {
            BBButton("New project", onClick = { onEditCustomer("new") }, style = BBButtonStyle.Primary, small = true, leadingIcon = Icons.Outlined.Add)
            FilterPill(
                text = if (vm.includeArchived) "Hiding none" else "Active only",
                onClick = { vm.toggleArchived() },
                showCaret = false,
            )
        }

        vm.actionError?.let {
            Box(Modifier.padding(horizontal = 16.dp)) { MessageBox(it, MessageKind.Error) }
        }
        vm.actionInfo?.let {
            Box(Modifier.padding(horizontal = 16.dp)) { MessageBox(it, MessageKind.Info) }
        }

        ScreenState(loading = vm.loading, error = vm.error, onRetry = { vm.load() }) {
            if (vm.customers.isEmpty()) {
                EmptyState(
                    title = "No projects yet",
                    subtitle = "Create a project to connect a ticketing source.",
                    icon = Icons.Outlined.Business,
                    action = { BBButton("New project", onClick = { onEditCustomer("new") }, style = BBButtonStyle.Primary, small = true) },
                )
            } else {
                LazyColumn(
                    contentPadding = PaddingValues(16.dp),
                    verticalArrangement = Arrangement.spacedBy(14.dp),
                ) {
                    items(vm.customers, key = { it.id }) { customer ->
                        CustomerCard(
                            customer = customer,
                            onEdit = { onEditCustomer(customer.id) },
                            onSync = { vm.syncNow(customer.id) },
                            onDelete = { deleteFor = customer },
                        )
                    }
                }
            }
        }
    }

    deleteFor?.let { c ->
        ConfirmDialog(
            title = "Delete project",
            message = "Delete ${c.name}? Imported tasks for this project may be affected.",
            confirmText = "Delete",
            danger = true,
            onConfirm = { deleteFor = null; vm.delete(c.id) },
            onDismiss = { deleteFor = null },
        )
    }
}

@OptIn(ExperimentalLayoutApi::class)
@Composable
private fun CustomerCard(
    customer: Customer,
    onEdit: () -> Unit,
    onSync: () -> Unit,
    onDelete: () -> Unit,
) {
    val p = BB.colors
    val t = customer.ticketing
    BBCard(modifier = Modifier.fillMaxWidth(), topStrip = true) {
        Column(verticalArrangement = Arrangement.spacedBy(10.dp)) {
            Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceBetween, verticalAlignment = Alignment.CenterVertically) {
                Text(
                    customer.name.ifBlank { "(unnamed)" },
                    style = MaterialTheme.typography.titleLarge,
                    color = p.text,
                    modifier = Modifier.weight(1f),
                )
                Row(horizontalArrangement = Arrangement.spacedBy(6.dp), verticalAlignment = Alignment.CenterVertically) {
                    BBBadge(t.type, color = p.accent)
                    if (customer.archived) BBBadge("Archived", color = p.err)
                }
            }

            t.projectKey?.takeIf { it.isNotBlank() }?.let {
                Text(it, fontFamily = SplineMono, style = MaterialTheme.typography.labelSmall, color = p.muted)
            }

            Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp)) {
                when (t.lastSyncStatus) {
                    "ok" -> {
                        Dot(p.ok)
                        Text("Synced ${relativeTime(t.lastSyncAt)}".trim(), style = MaterialTheme.typography.bodySmall, color = p.muted)
                    }
                    "error" -> {
                        Dot(p.err)
                        Text(t.lastSyncError ?: "Sync error", style = MaterialTheme.typography.bodySmall, color = p.err, maxLines = 2)
                    }
                    else -> {
                        Dot(p.muted)
                        Text("Not synced", style = MaterialTheme.typography.bodySmall, color = p.muted)
                    }
                }
            }

            if (!t.hasCredentials && t.type != "demo") {
                BBBadge("No credentials", color = p.warn)
            }

            FlowRow(horizontalArrangement = Arrangement.spacedBy(8.dp), verticalArrangement = Arrangement.spacedBy(8.dp)) {
                BBButton("Edit", onClick = onEdit, style = BBButtonStyle.Default, small = true)
                BBButton("Sync now", onClick = onSync, style = BBButtonStyle.Default, small = true)
                BBButton("Delete", onClick = onDelete, style = BBButtonStyle.Danger, small = true)
            }
        }
    }
}

@Composable
private fun Dot(color: androidx.compose.ui.graphics.Color) {
    Box(Modifier.size(8.dp).clip(CircleShape).background(color))
}
