package com.anypreta.bountyboard.ui.task

import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.heightIn
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.Checkbox
import androidx.compose.material3.CheckboxDefaults
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.text.input.KeyboardType
import androidx.compose.ui.unit.dp
import com.anypreta.bountyboard.data.model.Task
import com.anypreta.bountyboard.data.net.ChecklistItem
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.FilterPill
import com.anypreta.bountyboard.ui.theme.BB
import com.anypreta.bountyboard.ui.util.formatBounty

@Composable
fun TimeDialog(onConfirm: (Int, String?) -> Unit, onDismiss: () -> Unit) {
    val p = BB.colors
    var minutes by remember { mutableStateOf("") }
    var note by remember { mutableStateOf("") }
    AlertDialog(
        onDismissRequest = onDismiss,
        containerColor = p.surface,
        title = { Text("Log time", style = MaterialTheme.typography.headlineSmall, color = p.text) },
        text = {
            Column(verticalArrangement = Arrangement.spacedBy(10.dp)) {
                BBTextField(minutes, { minutes = it.filter { c -> c.isDigit() } }, "Minutes", placeholder = "e.g. 90", keyboardType = KeyboardType.Number)
                BBTextField(note, { note = it }, "Note (optional)", singleLine = false, minLines = 2)
            }
        },
        confirmButton = {
            BBButton("Log", onClick = { minutes.toIntOrNull()?.let { onConfirm(it, note.ifBlank { null }) } }, enabled = (minutes.toIntOrNull() ?: 0) in 1..1440, style = BBButtonStyle.Primary, small = true)
        },
        dismissButton = { BBButton("Cancel", onClick = onDismiss, style = BBButtonStyle.Ghost, small = true) },
    )
}

@Composable
fun SubdivideDialog(onConfirm: (String?, Int?, Int?) -> Unit, onDismiss: () -> Unit) {
    val p = BB.colors
    var note by remember { mutableStateOf("") }
    var min by remember { mutableStateOf("") }
    var max by remember { mutableStateOf("") }
    AlertDialog(
        onDismissRequest = onDismiss,
        containerColor = p.surface,
        title = { Text("Subdivide task", style = MaterialTheme.typography.headlineSmall, color = p.text) },
        text = {
            Column(verticalArrangement = Arrangement.spacedBy(10.dp)) {
                Text("AI splits this task into smaller subtasks. Re-running replaces previous unpublished children.", style = MaterialTheme.typography.bodyMedium, color = p.muted)
                BBTextField(note, { note = it }, "Guidance note (optional)", placeholder = "split backend/frontend…", singleLine = false, minLines = 2)
                Row(horizontalArrangement = Arrangement.spacedBy(10.dp)) {
                    BBTextField(min, { min = it.filter { c -> c.isDigit() } }, "Min tasks", keyboardType = KeyboardType.Number, modifier = Modifier.fillMaxWidth(0.5f))
                    BBTextField(max, { max = it.filter { c -> c.isDigit() } }, "Max tasks", keyboardType = KeyboardType.Number, modifier = Modifier.fillMaxWidth())
                }
            }
        },
        confirmButton = { BBButton("Subdivide", onClick = { onConfirm(note.ifBlank { null }, min.toIntOrNull(), max.toIntOrNull()) }, style = BBButtonStyle.Primary, small = true) },
        dismissButton = { BBButton("Cancel", onClick = onDismiss, style = BBButtonStyle.Ghost, small = true) },
    )
}

@Composable
fun AssignAiDialog(onConfirm: (String?, String?, String?) -> Unit, onDismiss: () -> Unit) {
    val p = BB.colors
    var repo by remember { mutableStateOf("") }
    var branch by remember { mutableStateOf("") }
    var instructions by remember { mutableStateOf("") }
    AlertDialog(
        onDismissRequest = onDismiss,
        containerColor = p.surface,
        title = { Text("Assign to AI performer", style = MaterialTheme.typography.headlineSmall, color = p.text) },
        text = {
            Column(verticalArrangement = Arrangement.spacedBy(10.dp)) {
                BBTextField(repo, { repo = it }, "Repository URL (optional)", placeholder = "https://github.com/…", keyboardType = KeyboardType.Uri)
                BBTextField(branch, { branch = it }, "Branch (optional)")
                BBTextField(instructions, { instructions = it }, "Extra instructions (optional)", singleLine = false, minLines = 3)
            }
        },
        confirmButton = { BBButton("Create job", onClick = { onConfirm(repo, branch, instructions) }, style = BBButtonStyle.Primary, small = true) },
        dismissButton = { BBButton("Cancel", onClick = onDismiss, style = BBButtonStyle.Ghost, small = true) },
    )
}

@Composable
fun ReviewDialog(
    task: Task,
    onConfirm: (approve: Boolean, note: String?, checklist: List<ChecklistItem>) -> Unit,
    onDismiss: () -> Unit,
) {
    val p = BB.colors
    val criteria = task.acceptanceCriteria ?: emptyList()
    val checks = remember { mutableStateMapOf<Int, Boolean>() }
    var note by remember { mutableStateOf("") }
    var approve by remember { mutableStateOf(true) }
    AlertDialog(
        onDismissRequest = onDismiss,
        containerColor = p.surface,
        title = { Text("Review submission", style = MaterialTheme.typography.headlineSmall, color = p.text) },
        text = {
            Column(
                Modifier.heightIn(max = 420.dp).verticalScroll(rememberScrollState()),
                verticalArrangement = Arrangement.spacedBy(8.dp),
            ) {
                if (criteria.isNotEmpty()) {
                    Text("Acceptance criteria", style = MaterialTheme.typography.titleSmall, color = p.text)
                    criteria.forEachIndexed { i, c ->
                        Row(verticalAlignment = Alignment.CenterVertically) {
                            Checkbox(
                                checked = checks[i] ?: false,
                                onCheckedChange = { checks[i] = it },
                                colors = CheckboxDefaults.colors(checkedColor = p.ok, uncheckedColor = p.border),
                            )
                            Text(c, style = MaterialTheme.typography.bodyMedium, color = p.text)
                        }
                    }
                }
                Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
                    BBButton("Approve", onClick = { approve = true }, style = if (approve) BBButtonStyle.Primary else BBButtonStyle.Ghost, small = true)
                    BBButton("Request changes", onClick = { approve = false }, style = if (!approve) BBButtonStyle.Primary else BBButtonStyle.Ghost, small = true)
                }
                Text(if (approve) "Approving freezes the bounty into the ledger." else "Requesting changes returns the task to the developer.", style = MaterialTheme.typography.labelSmall, color = if (approve) p.ok else p.warn)
                BBTextField(note, { note = it }, "Review note (optional)", singleLine = false, minLines = 2)
            }
        },
        confirmButton = {
            BBButton(
                if (approve) "Approve" else "Request changes",
                onClick = {
                    val checklist = criteria.mapIndexed { i, c -> ChecklistItem(c, checks[i] ?: false) }
                    onConfirm(approve, note.ifBlank { null }, checklist)
                },
                style = if (approve) BBButtonStyle.Primary else BBButtonStyle.Default,
                small = true,
            )
        },
        dismissButton = { BBButton("Cancel", onClick = onDismiss, style = BBButtonStyle.Ghost, small = true) },
    )
}

@Composable
fun EditTaskDialog(task: Task, onConfirm: (String, String, List<String>, Double, Double) -> Unit, onDismiss: () -> Unit) {
    val p = BB.colors
    var title by remember { mutableStateOf(task.title) }
    var description by remember { mutableStateOf(task.description) }
    var ac by remember { mutableStateOf((task.acceptanceCriteria ?: emptyList()).joinToString("\n")) }
    var coefficient by remember { mutableStateOf(task.effortCoefficient.toString()) }
    var budget by remember { mutableStateOf(formatBounty(task.budget)) }

    val coef = coefficient.toDoubleOrNull() ?: task.effortCoefficient
    val bud = budget.toDoubleOrNull() ?: task.budget
    val previewBounty = (coef * bud)

    AlertDialog(
        onDismissRequest = onDismiss,
        containerColor = p.surface,
        title = { Text("Edit task", style = MaterialTheme.typography.headlineSmall, color = p.text) },
        text = {
            Column(
                Modifier.heightIn(max = 460.dp).verticalScroll(rememberScrollState()),
                verticalArrangement = Arrangement.spacedBy(10.dp),
            ) {
                BBTextField(title, { title = it }, "Title")
                BBTextField(description, { description = it }, "Description", singleLine = false, minLines = 4)
                BBTextField(ac, { ac = it }, "Acceptance criteria (one per line)", singleLine = false, minLines = 3)
                Row(horizontalArrangement = Arrangement.spacedBy(10.dp)) {
                    BBTextField(coefficient, { coefficient = it }, "Coefficient", keyboardType = KeyboardType.Decimal, modifier = Modifier.fillMaxWidth(0.5f))
                    BBTextField(budget, { budget = it }, "Budget", keyboardType = KeyboardType.Decimal, modifier = Modifier.fillMaxWidth())
                }
                Text("Bounty preview: ◈ ${formatBounty(previewBounty)}", style = MaterialTheme.typography.titleSmall, color = p.accent)
            }
        },
        confirmButton = {
            BBButton(
                "Save",
                onClick = {
                    val acList = ac.split("\n").map { it.trim() }.filter { it.isNotEmpty() }
                    onConfirm(title.trim(), description.trim(), acList, coef, bud)
                },
                enabled = title.isNotBlank(),
                style = BBButtonStyle.Primary,
                small = true,
            )
        },
        dismissButton = { BBButton("Cancel", onClick = onDismiss, style = BBButtonStyle.Ghost, small = true) },
    )
}
