package ru.forbion.f7cloud.feature.deck

import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.clickable
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.Row
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.heightIn
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.verticalScroll
import androidx.compose.material3.Checkbox
import androidx.compose.material3.CheckboxDefaults
import androidx.compose.material3.DatePicker
import androidx.compose.material3.DatePickerDialog
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.material3.rememberDatePickerState
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.graphics.Color
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.compose.ui.window.Dialog
import androidx.compose.ui.window.DialogProperties
import ru.forbion.f7cloud.core.designsystem.F7Colors
import ru.forbion.f7cloud.core.designsystem.F7OutlinedField
import ru.forbion.f7cloud.core.designsystem.F7PrimaryButton
import ru.forbion.f7cloud.core.designsystem.F7SecondaryButton
import java.time.Instant
import java.time.ZoneId
import java.time.format.DateTimeFormatter

@OptIn(ExperimentalMaterial3Api::class, ExperimentalLayoutApi::class)
@Composable
fun DeckCardSheet(
    card: DeckCard,
    boardLabels: List<DeckLabel>,
    stacks: List<DeckStack>,
    canEdit: Boolean,
    busy: Boolean,
    onDismiss: () -> Unit,
    onToggleDone: () -> Unit,
    onSave: (title: String, description: String, duedate: String?) -> Unit,
    onToggleLabel: (DeckLabel) -> Unit,
    onMove: (targetStackId: Int) -> Unit,
    onArchive: () -> Unit,
    onDelete: () -> Unit,
) {
    var title by remember(card.id) { mutableStateOf(card.title) }
    var description by remember(card.id) { mutableStateOf(card.description) }
    // duedate храним как ISO-строку (как отдаёт/принимает Deck), null = без срока
    var duedate by remember(card.id) { mutableStateOf(card.duedate) }
    var datePickerOpen by remember { mutableStateOf(false) }

    Dialog(onDismissRequest = onDismiss, properties = DialogProperties(usePlatformDefaultWidth = false)) {
        Surface(
            modifier = Modifier.fillMaxWidth(0.96f).heightIn(max = 680.dp),
            shape = RoundedCornerShape(16.dp),
            color = Color.White,
        ) {
            Column(
                modifier = Modifier.verticalScroll(rememberScrollState()).padding(16.dp),
                verticalArrangement = Arrangement.spacedBy(12.dp),
            ) {
                // Done + заголовок
                Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp)) {
                    Checkbox(
                        checked = card.done,
                        onCheckedChange = { if (canEdit) onToggleDone() },
                        enabled = canEdit && !busy,
                        colors = CheckboxDefaults.colors(checkedColor = F7Colors.Primary),
                    )
                    Text(
                        if (card.done) "Выполнена" else "Не выполнена",
                        style = MaterialTheme.typography.bodyMedium,
                        color = F7Colors.TextSecondary,
                    )
                }
                F7OutlinedField(value = title, onValueChange = { title = it }, label = "Название")
                F7OutlinedField(value = description, onValueChange = { description = it }, label = "Описание", minLines = 3)

                // Срок
                Text("Срок", style = MaterialTheme.typography.bodyMedium, color = F7Colors.TextSecondary)
                Row(
                    modifier = Modifier
                        .fillMaxWidth()
                        .heightIn(min = 36.dp)
                        .clip(RoundedCornerShape(10.dp))
                        .background(F7Colors.SurfaceMuted)
                        .clickable(enabled = canEdit) { datePickerOpen = true }
                        .padding(horizontal = 10.dp, vertical = 8.dp),
                    verticalAlignment = Alignment.CenterVertically,
                ) {
                    Text(
                        duedate?.let { formatDeckDue(it) } ?: "Без срока",
                        modifier = Modifier.weight(1f),
                        style = MaterialTheme.typography.bodyMedium,
                        color = if (duedate != null) F7Colors.TextPrimary else F7Colors.TextSecondary,
                    )
                    if (duedate != null) {
                        Text("Сбросить", color = F7Colors.Primary, style = MaterialTheme.typography.bodyMedium, modifier = Modifier.clickable { duedate = null })
                    }
                }

                // Метки доски
                if (boardLabels.isNotEmpty()) {
                    Text("Метки", style = MaterialTheme.typography.bodyMedium, color = F7Colors.TextSecondary)
                    FlowRow(horizontalArrangement = Arrangement.spacedBy(6.dp), verticalArrangement = Arrangement.spacedBy(6.dp)) {
                        boardLabels.forEach { label ->
                            val active = card.labels.any { it.id == label.id }
                            Box(
                                modifier = Modifier
                                    .clip(RoundedCornerShape(4.dp))
                                    .background(
                                        (parseDeckColor(label.color) ?: F7Colors.Primary)
                                            .copy(alpha = if (active) 0.35f else 0.12f),
                                    )
                                    .border(
                                        if (active) 2.dp else 1.dp,
                                        parseDeckColor(label.color) ?: F7Colors.Primary,
                                        RoundedCornerShape(4.dp),
                                    )
                                    .clickable(enabled = canEdit && !busy) { onToggleLabel(label) }
                                    .padding(horizontal = 8.dp, vertical = 3.dp),
                            ) {
                                Text(label.title, style = MaterialTheme.typography.labelMedium, color = F7Colors.TextPrimary)
                            }
                        }
                    }
                }

                // Переместить в колонку
                if (canEdit && stacks.size > 1) {
                    Text("Колонка", style = MaterialTheme.typography.bodyMedium, color = F7Colors.TextSecondary)
                    FlowRow(horizontalArrangement = Arrangement.spacedBy(6.dp), verticalArrangement = Arrangement.spacedBy(6.dp)) {
                        stacks.forEach { stack ->
                            val current = stack.id == card.stackId
                            Box(
                                modifier = Modifier
                                    .clip(RoundedCornerShape(100.dp))
                                    .background(if (current) F7Colors.PrimaryLight else F7Colors.SurfaceMuted)
                                    .clickable(enabled = !current && !busy) { onMove(stack.id) }
                                    .padding(horizontal = 10.dp, vertical = 4.dp),
                            ) {
                                Text(stack.title, style = MaterialTheme.typography.bodyMedium, color = F7Colors.TextPrimary)
                            }
                        }
                    }
                }

                if (canEdit) {
                    Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
                        F7SecondaryButton("Закрыть", onClick = onDismiss, modifier = Modifier.weight(1f))
                        F7PrimaryButton(
                            text = if (busy) "…" else "Сохранить",
                            onClick = { onSave(title, description, duedate) },
                            enabled = !busy && title.isNotBlank(),
                            modifier = Modifier.weight(1f),
                        )
                    }
                    Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
                        F7SecondaryButton("В архив", onClick = onArchive, enabled = !busy, modifier = Modifier.weight(1f))
                        F7SecondaryButton("Удалить", onClick = onDelete, enabled = !busy, modifier = Modifier.weight(1f))
                    }
                } else {
                    F7SecondaryButton("Закрыть", onClick = onDismiss, modifier = Modifier.fillMaxWidth())
                }
            }
        }
    }

    if (datePickerOpen) {
        val initMillis = duedate?.let { parseDeckDueMillis(it) }
            ?: System.currentTimeMillis()
        val pickerState = rememberDatePickerState(initialSelectedDateMillis = initMillis)
        DatePickerDialog(
            onDismissRequest = { datePickerOpen = false },
            confirmButton = {
                TextButton(onClick = {
                    pickerState.selectedDateMillis?.let { millis ->
                        // Deck принимает ISO-8601 (в полдень UTC достаточно для «дня»)
                        val instant = Instant.ofEpochMilli(millis)
                        duedate = DateTimeFormatter.ISO_INSTANT.format(instant)
                    }
                    datePickerOpen = false
                }) { Text("ОК", color = F7Colors.Primary) }
            },
            dismissButton = {
                TextButton(onClick = { datePickerOpen = false }) { Text("Отмена", color = F7Colors.TextSecondary) }
            },
        ) { DatePicker(state = pickerState) }
    }
}

@Composable
fun DeckTextPromptDialog(
    title: String,
    label: String,
    confirmText: String,
    onConfirm: (String) -> Unit,
    onDismiss: () -> Unit,
) {
    var text by remember { mutableStateOf("") }
    Dialog(onDismissRequest = onDismiss) {
        Surface(shape = RoundedCornerShape(16.dp), color = Color.White) {
            Column(modifier = Modifier.padding(16.dp), verticalArrangement = Arrangement.spacedBy(12.dp)) {
                Text(
                    title,
                    style = MaterialTheme.typography.titleMedium.copy(fontSize = 18.sp),
                    fontWeight = FontWeight.SemiBold,
                    color = F7Colors.TextPrimary,
                )
                F7OutlinedField(value = text, onValueChange = { text = it }, label = label)
                Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {
                    F7SecondaryButton("Отмена", onClick = onDismiss, modifier = Modifier.weight(1f))
                    F7PrimaryButton(
                        text = confirmText,
                        onClick = { onConfirm(text) },
                        enabled = text.isNotBlank(),
                        modifier = Modifier.weight(1f),
                    )
                }
            }
        }
    }
}


/** Парсит ISO-строку срока Deck в миллисекунды (для инициализации пикера). */
internal fun parseDeckDueMillis(iso: String): Long? = runCatching {
    Instant.parse(iso).toEpochMilli()
}.getOrElse {
    runCatching {
        java.time.OffsetDateTime.parse(iso).toInstant().toEpochMilli()
    }.getOrNull()
}

/** Отображение срока: «12 мар». */
internal fun formatDeckDue(iso: String): String {
    val millis = parseDeckDueMillis(iso) ?: return iso.take(10)
    val date = Instant.ofEpochMilli(millis).atZone(ZoneId.systemDefault()).toLocalDate()
    return date.format(DateTimeFormatter.ofPattern("d MMM"))
}
