package com.harshmallow.pilottoolkit.ui.components

import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.material3.*
import androidx.compose.runtime.*
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.FontFamily
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.harshmallow.pilottoolkit.data.WarningLevel
import com.harshmallow.pilottoolkit.data.WeightWarning
import com.harshmallow.pilottoolkit.ui.theme.ToolkitTheme

@Composable
fun ToolkitTextField(
    value: String, onValueChange: (String) -> Unit,
    label: String, placeholder: String = "",
    keyboardType: KeyboardType = KeyboardType.Text,
    sublabel: String? = null
) {
    val colors = ToolkitTheme.colors
    if (label.isNotEmpty()) {
        Row(verticalAlignment = Alignment.CenterVertically) {
            FieldLabel(label)
            if (sublabel != null) {
                Spacer(Modifier.width(6.dp))
                Text(sublabel, fontSize = 10.sp, color = colors.textMuted, fontWeight = FontWeight.Normal)
            }
        }
    }
    OutlinedTextField(
        value = value, onValueChange = onValueChange,
        placeholder = { Text(placeholder, fontSize = 14.sp, color = colors.textMuted) },
        modifier = Modifier.fillMaxWidth(),
        singleLine = true,
        shape = RoundedCornerShape(8.dp),
        keyboardOptions = KeyboardOptions(keyboardType = keyboardType),
        colors = OutlinedTextFieldDefaults.colors(
            focusedBorderColor = colors.accent,
            unfocusedBorderColor = colors.border,
            focusedTextColor = colors.text,
            unfocusedTextColor = colors.text,
            cursorColor = colors.accent,
            focusedContainerColor = Color.Transparent,
            unfocusedContainerColor = Color.Transparent,
        )
    )
}

@Composable
fun FieldLabel(text: String) {
    val colors = ToolkitTheme.colors
    Text(text, fontSize = 11.sp, fontWeight = FontWeight.Bold, color = colors.textMuted,
        letterSpacing = 0.5.sp, modifier = Modifier.padding(bottom = 6.dp))
}

@Composable
fun ClearButton(onClick: () -> Unit) {
    val colors = ToolkitTheme.colors
    TextButton(onClick = onClick, modifier = Modifier.fillMaxWidth()) {
        Text("Clear", fontSize = 13.sp, fontWeight = FontWeight.SemiBold, color = colors.textMuted)
    }
}

@Composable
fun ResultCard(content: @Composable ColumnScope.() -> Unit) {
    val colors = ToolkitTheme.colors
    Card(
        modifier = Modifier.fillMaxWidth(),
        shape = RoundedCornerShape(10.dp),
        colors = CardDefaults.cardColors(containerColor = colors.resultBg),
        border = CardDefaults.outlinedCardBorder().let {
            androidx.compose.foundation.BorderStroke(1.dp, colors.resultBorder)
        }
    ) {
        Column(modifier = Modifier.padding(20.dp), content = content)
    }
}

@Composable
fun ResultRow(label: String, value: String, unit: String? = null) {
    val colors = ToolkitTheme.colors
    Row(Modifier.fillMaxWidth().padding(vertical = 4.dp),
        horizontalArrangement = Arrangement.SpaceBetween, verticalAlignment = Alignment.CenterVertically) {
        Text(label, fontSize = 14.sp, fontWeight = FontWeight.Medium, color = colors.textSecondary)
        Row(verticalAlignment = Alignment.Bottom) {
            Text(value, fontSize = 20.sp, fontWeight = FontWeight.Bold, color = colors.accent,
                fontFamily = FontFamily.Monospace)
            if (unit != null) {
                Spacer(Modifier.width(4.dp))
                Text(unit, fontSize = 12.sp, color = colors.textMuted)
            }
        }
    }
}

@Composable
fun ResultRowColored(label: String, value: String, color: Color) {
    val colors = ToolkitTheme.colors
    Row(Modifier.fillMaxWidth().padding(vertical = 4.dp),
        horizontalArrangement = Arrangement.SpaceBetween, verticalAlignment = Alignment.CenterVertically) {
        Text(label, fontSize = 14.sp, fontWeight = FontWeight.Medium, color = if (color == colors.danger) color else colors.textSecondary)
        Text(value, fontSize = 20.sp, fontWeight = FontWeight.Bold, color = color, fontFamily = FontFamily.Monospace)
    }
}

@Composable
fun ResultDivider() {
    val colors = ToolkitTheme.colors
    HorizontalDivider(modifier = Modifier.padding(vertical = 10.dp), color = colors.border)
}

@Composable
fun SegmentedSelector(options: List<String>, selected: Int, onSelect: (Int) -> Unit) {
    val colors = ToolkitTheme.colors
    Row(Modifier.fillMaxWidth().clip(RoundedCornerShape(8.dp)).border(1.dp, colors.border, RoundedCornerShape(8.dp))) {
        options.forEachIndexed { i, label ->
            val isActive = i == selected
            Box(
                modifier = Modifier.weight(1f)
                    .background(if (isActive) colors.accent.copy(alpha = 0.12f) else Color.Transparent)
                    .clickable { onSelect(i) }
                    .padding(vertical = 10.dp),
                contentAlignment = Alignment.Center
            ) {
                Text(label, fontSize = 13.sp,
                    fontWeight = if (isActive) FontWeight.Bold else FontWeight.Medium,
                    color = if (isActive) colors.accent else colors.textMuted)
            }
        }
    }
}

@Composable
fun WarningBanner(warning: WeightWarning) {
    val colors = ToolkitTheme.colors
    val bg = if (warning.level == WarningLevel.DANGER) colors.dangerBg else colors.warningBg
    val border = if (warning.level == WarningLevel.DANGER) colors.dangerBorder else colors.warningBorder
    val fg = if (warning.level == WarningLevel.DANGER) colors.danger else colors.warning
    val icon = if (warning.level == WarningLevel.DANGER) "⛔" else "⚠"
    Box(modifier = Modifier.fillMaxWidth().clip(RoundedCornerShape(8.dp))
        .background(bg).border(1.dp, border, RoundedCornerShape(8.dp)).padding(12.dp)) {
        Text("$icon ${warning.message}", fontSize = 13.sp, fontWeight = FontWeight.Medium, color = fg)
    }
}

@Composable
fun UnavailableMessage(message: String) {
    val colors = ToolkitTheme.colors
    Box(modifier = Modifier.fillMaxWidth().clip(RoundedCornerShape(8.dp))
        .background(colors.surfaceAlt).border(1.dp, colors.border, RoundedCornerShape(8.dp)).padding(16.dp),
        contentAlignment = Alignment.Center) {
        Text(message, fontSize = 13.sp, color = colors.textMuted, textAlign = TextAlign.Center, lineHeight = 20.sp)
    }
}

@Composable
fun ToggleSwitch(
    checked: Boolean, onCheckedChange: (Boolean) -> Unit,
    labelLeft: String, labelRight: String
) {
    val colors = ToolkitTheme.colors
    Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp)) {
        Text(labelLeft, fontSize = 12.sp, fontWeight = if (!checked) FontWeight.Bold else FontWeight.Normal,
            color = if (!checked) colors.accent else colors.textMuted)
        Switch(
            checked = checked, onCheckedChange = onCheckedChange,
            colors = SwitchDefaults.colors(
                checkedThumbColor = colors.accent,
                checkedTrackColor = colors.accent.copy(alpha = 0.25f),
                uncheckedThumbColor = colors.accent,
                uncheckedTrackColor = colors.accent.copy(alpha = 0.25f),
            ),
            modifier = Modifier.height(24.dp)
        )
        Text(labelRight, fontSize = 12.sp, fontWeight = if (checked) FontWeight.Bold else FontWeight.Normal,
            color = if (checked) colors.accent else colors.textMuted)
    }
}
