package com.anypreta.bountyboard.ui.developer

import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
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.Search
import androidx.compose.material.icons.outlined.Sell
import androidx.compose.material.icons.outlined.Storefront
import androidx.compose.material3.DropdownMenu
import androidx.compose.material3.DropdownMenuItem
import androidx.compose.material3.Icon
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.compose.collectAsStateWithLifecycle
import androidx.lifecycle.viewmodel.compose.viewModel
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.BBTextField
import com.anypreta.bountyboard.ui.components.ClaimDialog
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.TaskCard
import com.anypreta.bountyboard.ui.theme.BB

@Composable
fun BoardScreen(onOpenTask: (String) -> Unit) {
    val container = LocalAppContainer.current
    val vm: BoardViewModel = viewModel(factory = containerVMFactory(container) { BoardViewModel(it) })
    val me by container.session.user.collectAsStateWithLifecycle()
    val p = BB.colors

    var customerMenu by remember { mutableStateOf(false) }
    var claimFor by remember { mutableStateOf<String?>(null) }

    Column(Modifier.fillMaxWidth()) {
        // Search + filters
        Column(Modifier.padding(horizontal = 16.dp, vertical = 12.dp), verticalArrangement = Arrangement.spacedBy(10.dp)) {
            BBTextField(
                value = vm.query,
                onValueChange = { vm.query = it },
                label = "Search the board",
                placeholder = "Title or description…",
                leadingIcon = Icons.Outlined.Search,
            )
            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 })
                        }
                    }
                }
                FilterPill(
                    text = if (vm.sortByBounty) "Highest bounty" else "Newest",
                    icon = Icons.Outlined.Sell,
                    onClick = { vm.setSort(!vm.sortByBounty) },
                )
                BBButton("Search", onClick = { vm.load() }, style = BBButtonStyle.Primary, small = true)
            }
        }

        ScreenState(loading = vm.loading, error = vm.error, onRetry = { vm.load() }) {
            if (vm.tasks.isEmpty()) {
                EmptyState(
                    title = "No bounties available",
                    subtitle = "Published tasks from consultants who've added you to their pool appear here.",
                    icon = Icons.Outlined.Storefront,
                )
            } else {
                LazyColumn(
                    contentPadding = androidx.compose.foundation.layout.PaddingValues(16.dp),
                    verticalArrangement = Arrangement.spacedBy(14.dp),
                ) {
                    items(vm.tasks, key = { it.id }) { task ->
                        val myId = me?.id
                        val claimed = task.claimRequests?.any { it.developerId == myId } == true
                        TaskCard(
                            task = task,
                            onClick = { onOpenTask(task.id) },
                            customerName = vm.customerName(task.customerId),
                            showAge = true,
                            footer = {
                                Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceBetween, verticalAlignment = Alignment.CenterVertically) {
                                    val others = (task.claimRequests?.size ?: 0)
                                    if (others > 0) {
                                        Text(
                                            "$others claim${if (others == 1) "" else "s"}",
                                            style = MaterialTheme.typography.labelSmall,
                                            color = p.muted,
                                        )
                                    } else {
                                        androidx.compose.foundation.layout.Spacer(Modifier)
                                    }
                                    if (claimed) {
                                        BBBadge("Requested by you", color = p.ok)
                                    } else {
                                        BBButton("Request assignment", onClick = { claimFor = task.id }, style = BBButtonStyle.Primary, small = true)
                                    }
                                }
                            },
                        )
                    }
                }
            }
        }
    }

    claimFor?.let { taskId ->
        ClaimDialog(
            onDismiss = { claimFor = null },
            onConfirm = { note ->
                vm.claim(taskId, note) { claimFor = null }
            },
        )
    }
}
