package com.anypreta.bountyboard.ui.consultant

import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
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.layout.padding
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.outlined.FilterList
import androidx.compose.material.icons.outlined.Storefront
import androidx.compose.material3.DropdownMenu
import androidx.compose.material3.DropdownMenuItem
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.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.data.model.Task
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.EmptyState
import com.anypreta.bountyboard.ui.components.FilterPill
import com.anypreta.bountyboard.ui.components.ScreenState
import com.anypreta.bountyboard.ui.components.SectionLabel
import com.anypreta.bountyboard.ui.components.TaskCard
import com.anypreta.bountyboard.ui.theme.BB
import com.anypreta.bountyboard.ui.util.statusLabel
import kotlinx.coroutines.launch

private val STATUS_FILTERS =
    listOf("imported", "atomizing", "atomized", "published", "claim_requested")

@Composable
fun ConsultantBoardScreen(onOpenTask: (String) -> Unit) {
    val container = LocalAppContainer.current
    val vm: ConsultantBoardViewModel =
        viewModel(factory = containerVMFactory(container) { ConsultantBoardViewModel(it) })
    val p = BB.colors

    var customerMenu by remember { mutableStateOf(false) }
    var statusMenu by remember { mutableStateOf(false) }

    Column(Modifier.fillMaxWidth()) {
        Column(
            Modifier.padding(horizontal = 16.dp, vertical = 12.dp),
            verticalArrangement = Arrangement.spacedBy(10.dp),
        ) {
            Row(
                verticalAlignment = Alignment.CenterVertically,
                horizontalArrangement = Arrangement.spacedBy(8.dp),
            ) {
                Box {
                    FilterPill(
                        text = vm.customerId?.let { vm.customerName(it) } ?: "All projects",
                        icon = Icons.Outlined.FilterList,
                        onClick = { customerMenu = true },
                    )
                    DropdownMenu(expanded = customerMenu, onDismissRequest = { customerMenu = false }) {
                        DropdownMenuItem(
                            text = { Text("All projects") },
                            onClick = { vm.setCustomer(null); customerMenu = false },
                        )
                        vm.customers.forEach { c ->
                            DropdownMenuItem(
                                text = { Text(c.name) },
                                onClick = { vm.setCustomer(c.id); customerMenu = false },
                            )
                        }
                    }
                }
                Box {
                    FilterPill(
                        text = vm.status?.let { statusLabel(it) } ?: "All statuses",
                        onClick = { statusMenu = true },
                    )
                    DropdownMenu(expanded = statusMenu, onDismissRequest = { statusMenu = false }) {
                        DropdownMenuItem(
                            text = { Text("All statuses") },
                            onClick = { vm.applyStatus(null); statusMenu = false },
                        )
                        STATUS_FILTERS.forEach { s ->
                            DropdownMenuItem(
                                text = { Text(statusLabel(s)) },
                                onClick = { vm.applyStatus(s); statusMenu = false },
                            )
                        }
                    }
                }
            }
            Text(
                "Tap a task to subdivide, extend, edit or publish.",
                style = MaterialTheme.typography.bodySmall,
                color = p.muted,
            )
        }

        ScreenState(loading = vm.loading, error = vm.error, onRetry = { vm.load() }) {
            if (vm.tasks.isEmpty()) {
                EmptyState(
                    title = "No tasks",
                    subtitle = "Imported tickets show up here after a project sync — then you can atomize and publish them.",
                    icon = Icons.Outlined.Storefront,
                )
            } else {
                val byCustomer = vm.customers.filter { c -> vm.tasks.any { it.customerId == c.id } }
                val unknown = vm.tasks.filter { t -> vm.customers.none { it.id == t.customerId } }

                LazyColumn(
                    contentPadding = PaddingValues(16.dp),
                    verticalArrangement = Arrangement.spacedBy(14.dp),
                ) {
                    byCustomer.forEach { customer ->
                        val tasks = vm.tasks.filter { it.customerId == customer.id }
                        item(key = "header_${customer.id}") {
                            SectionLabel(customer.name, modifier = Modifier.padding(top = 4.dp))
                        }
                        items(tasks, key = { it.id }) { task ->
                            ConsultantTaskRow(task, onOpenTask, vm)
                        }
                    }
                    if (unknown.isNotEmpty()) {
                        item(key = "header_unknown") {
                            SectionLabel("Other", modifier = Modifier.padding(top = 4.dp))
                        }
                        items(unknown, key = { it.id }) { task ->
                            ConsultantTaskRow(task, onOpenTask, vm)
                        }
                    }
                }
            }
        }
    }
}

@Composable
private fun ConsultantTaskRow(
    task: Task,
    onOpenTask: (String) -> Unit,
    vm: ConsultantBoardViewModel,
) {
    TaskCard(
        task = task,
        onClick = { onOpenTask(task.id) },
        showStatus = true,
        footer = if (task.status == "atomized") {
            {
                Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.End) {
                    BBButton(
                        "Publish",
                        onClick = { vm.publish(task.id) },
                        style = BBButtonStyle.Primary,
                        small = true,
                    )
                }
            }
        } else null,
    )
}

class ConsultantBoardViewModel(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 tasks by mutableStateOf<List<Task>>(emptyList())
        private set

    var customerId by mutableStateOf<String?>(null)
        private set
    var status by mutableStateOf<String?>(null)
        private set

    init {
        load()
    }

    fun setCustomer(id: String?) {
        customerId = id; load()
    }

    fun applyStatus(s: String?) {
        status = s; load()
    }

    fun load() {
        loading = true; error = null
        viewModelScope.launch {
            try {
                val r = container.repo.call { consultantBoard(customerId = customerId, status = status) }
                customers = r.customers
                tasks = r.tasks
            } catch (e: Exception) {
                error = e.message
            } finally {
                loading = false
            }
        }
    }

    fun publish(id: String) {
        viewModelScope.launch {
            try {
                container.repo.call { publish(id) }
                load()
            } catch (e: Exception) {
                error = e.message
            }
        }
    }

    fun customerName(id: String): String? = customers.firstOrNull { it.id == id }?.name
}
