package com.harshmallow.pilottoolkit.ui.modules

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.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.text.font.FontFamily
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.harshmallow.pilottoolkit.data.Calculations
import com.harshmallow.pilottoolkit.ui.components.*
import com.harshmallow.pilottoolkit.ui.theme.ToolkitTheme

@Composable
fun FuelOrderModule(volumeUnit: String = "usgal") {
    val colors = ToolkitTheme.colors
    var tempInput by remember { mutableStateOf("") }
    var totalInput by remember { mutableStateOf("") }
    var onBoardInput by remember { mutableStateOf("") }
    var fuelInput by remember { mutableStateOf("") }
    var fuelManual by remember { mutableStateOf(false) }
    var useFahrenheit by remember { mutableStateOf(false) }
    var densityInput by remember { mutableStateOf("6.76") }
    var densityUnit by remember { mutableStateOf("lbgal") } // "sg" | "kgl" | "lbgal"

    // Auto-calculate Fuel Order from Total - OnBoard (unless user typed directly)
    LaunchedEffect(totalInput, onBoardInput, fuelManual) {
        if (fuelManual) return@LaunchedEffect
        val total = totalInput.toDoubleOrNull()
        val onBoard = onBoardInput.toDoubleOrNull()
        if (total != null && onBoard != null) {
            val diff = total - onBoard
            fuelInput = if (diff > 0) diff.toLong().toString() else "0"
        }
    }

    fun handleTempUnitToggle(toFahrenheit: Boolean) {
        val v = tempInput.toDoubleOrNull()
        if (v != null) {
            tempInput = if (toFahrenheit) {
                Math.round(v * 1.8 + 32.0).toString()
            } else {
                Math.round((v - 32.0) / 1.8).toString()
            }
        }
        useFahrenheit = toFahrenheit
    }

    val tempVal = tempInput.toDoubleOrNull()
    val fuelVal = fuelInput.toDoubleOrNull()
    val densityVal = densityInput.toDoubleOrNull()
    val tempC = if (tempVal != null && useFahrenheit) Calculations.fahrenheitToCelsius(tempVal) else tempVal
    val sg15 = if (densityVal != null) {
        if (densityUnit == "lbgal") densityVal / Calculations.LB_PER_GAL_PER_KGL else densityVal
    } else null
    val isAutoCalc = !fuelManual && totalInput.isNotEmpty() && onBoardInput.isNotEmpty()

    // Warnings
    data class FuelWarning(val level: String, val msg: String)
    val warning: FuelWarning? = when {
        tempC != null && tempC < -40 -> FuelWarning("danger", "Temperature is below −40°C. Approaching Jet-A freeze point.")
        tempC != null && tempC > 55 -> FuelWarning("warning", "Temperature is above +55°C. Verify conditions.")
        sg15 != null && sg15 < 0.775 -> FuelWarning("warning", "Density ${"%.3f".format(sg15)} SG is below Jet-A minimum spec (0.775).")
        sg15 != null && sg15 > 0.840 -> FuelWarning("warning", "Density ${"%.3f".format(sg15)} SG is above Jet-A maximum spec (0.840).")
        else -> null
    }

    // Results
    data class FuelResults(val usGal: Int, val impGal: Int, val liters: Int,
        val refDensityLbGal: String, val correctedLbGal: String, val tempCDisplay: Int)
    val results: FuelResults? = if (tempC != null && fuelVal != null && fuelVal > 0 && sg15 != null) {
        val corrected = Calculations.astmDensityLbGal(sg15, tempC)
        val usGal = fuelVal / corrected
        val liters = usGal * 3.78541
        val impGal = liters / 4.54609
        FuelResults(
            Calculations.roundUpToTen(usGal),
            Calculations.roundUpToTen(impGal),
            Calculations.roundUpToTen(liters),
            "%.3f".format(sg15 * Calculations.LB_PER_GAL_PER_KGL),
            "%.3f".format(corrected),
            tempC.toInt()
        )
    } else null

    // Unit conversion when switching density toggle
    fun handleDensityUnitChange(newUnit: String) {
        val v = densityInput.toDoubleOrNull()
        if (v != null) {
            val sg = if (densityUnit == "lbgal") v / Calculations.LB_PER_GAL_PER_KGL else v
            val converted = if (newUnit == "lbgal") sg * Calculations.LB_PER_GAL_PER_KGL else sg
            densityInput = if (newUnit == "lbgal") "%.2f".format(converted) else "%.3f".format(converted)
        }
        densityUnit = newUnit
    }

    Column(verticalArrangement = Arrangement.spacedBy(18.dp)) {
        // Temperature
        Column {
            FieldLabel("Ambient Temperature (${if (useFahrenheit) "°F" else "°C"})")
            Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(12.dp),
                verticalAlignment = Alignment.CenterVertically) {
                OutlinedTextField(
                    value = tempInput, onValueChange = { tempInput = it },
                    placeholder = { Text(if (useFahrenheit) "e.g. 59" else "e.g. 15", fontSize = 14.sp, color = colors.textMuted) },
                    modifier = Modifier.weight(2f), singleLine = true, shape = RoundedCornerShape(8.dp),
                    keyboardOptions = androidx.compose.foundation.text.KeyboardOptions(keyboardType = KeyboardType.Number),
                    colors = OutlinedTextFieldDefaults.colors(
                        focusedBorderColor = colors.accent, unfocusedBorderColor = colors.border,
                        focusedTextColor = colors.text, unfocusedTextColor = colors.text,
                        cursorColor = colors.accent,
                        focusedContainerColor = androidx.compose.ui.graphics.Color.Transparent,
                        unfocusedContainerColor = androidx.compose.ui.graphics.Color.Transparent,
                    )
                )
                Box(Modifier.weight(3f), contentAlignment = Alignment.CenterEnd) {
                    ToggleSwitch(checked = useFahrenheit, onCheckedChange = { handleTempUnitToggle(it) },
                        labelLeft = "°C", labelRight = "°F")
                }
            }
        }

        // Density at 15°C
        Column {
            FieldLabel("Fuel Density at 15°C")
            Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(12.dp),
                verticalAlignment = Alignment.CenterVertically) {
                OutlinedTextField(
                    value = densityInput, onValueChange = { densityInput = it },
                    placeholder = { Text(if (densityUnit == "lbgal") "e.g. 6.76" else "e.g. 0.810", fontSize = 14.sp, color = colors.textMuted) },
                    modifier = Modifier.weight(2f), singleLine = true, shape = RoundedCornerShape(8.dp),
                    keyboardOptions = androidx.compose.foundation.text.KeyboardOptions(keyboardType = KeyboardType.Decimal),
                    colors = OutlinedTextFieldDefaults.colors(
                        focusedBorderColor = colors.accent, unfocusedBorderColor = colors.border,
                        focusedTextColor = colors.text, unfocusedTextColor = colors.text,
                        cursorColor = colors.accent,
                        focusedContainerColor = androidx.compose.ui.graphics.Color.Transparent,
                        unfocusedContainerColor = androidx.compose.ui.graphics.Color.Transparent,
                    )
                )
                Box(Modifier.weight(3f), contentAlignment = Alignment.CenterEnd) {
                    // Three-way segmented control
                    Row(Modifier.clip(RoundedCornerShape(6.dp)).border(1.dp, colors.border, RoundedCornerShape(6.dp))) {
                        listOf("sg" to "SG", "kgl" to "kg/L", "lbgal" to "lb/gal").forEach { (key, label) ->
                            val active = densityUnit == key
                            Box(
                                Modifier.weight(1f)
                                    .background(if (active) colors.accent else androidx.compose.ui.graphics.Color.Transparent)
                                    .clickable { handleDensityUnitChange(key) }
                                    .padding(vertical = 8.dp),
                                contentAlignment = Alignment.Center
                            ) {
                                Text(label, fontSize = 11.sp, fontWeight = FontWeight.SemiBold,
                                    color = if (active) androidx.compose.ui.graphics.Color.White else colors.textSecondary)
                            }
                        }
                    }
                }
            }
            Text(
                "From fuel ticket. Jet-A spec: ${if (densityUnit == "lbgal") "6.47 – 7.01 lb/gal" else "0.775 – 0.840"}",
                fontSize = 10.sp, color = colors.textMuted, modifier = Modifier.padding(top = 4.dp)
            )
        }

        // Warning
        if (warning != null) {
            val bg = if (warning.level == "danger") colors.dangerBg else colors.warningBg
            val border = if (warning.level == "danger") colors.dangerBorder else colors.warningBorder
            val fg = if (warning.level == "danger") colors.danger else colors.warning
            val icon = if (warning.level == "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.msg}", fontSize = 13.sp, fontWeight = FontWeight.Medium, color = fg)
            }
        }

        // Optional: Total Required and Fuel On Board
        Column(modifier = Modifier.fillMaxWidth().clip(RoundedCornerShape(8.dp))
            .background(colors.surfaceAlt).border(1.dp, colors.border, RoundedCornerShape(8.dp))
            .padding(16.dp), verticalArrangement = Arrangement.spacedBy(12.dp)) {

            Text("OPTIONAL — CALCULATE FUEL ORDER", fontSize = 11.sp, fontWeight = FontWeight.Bold,
                color = colors.textMuted, letterSpacing = 0.5.sp)

            Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.spacedBy(12.dp)) {
                Column(Modifier.weight(1f)) {
                    ToolkitTextField(value = totalInput,
                        onValueChange = { totalInput = it; fuelManual = false },
                        label = "Total Required (lbs)", placeholder = "e.g. 12000",
                        keyboardType = KeyboardType.Number)
                }
                Column(Modifier.weight(1f)) {
                    ToolkitTextField(value = onBoardInput,
                        onValueChange = { onBoardInput = it; fuelManual = false },
                        label = "On Board (lbs)", placeholder = "e.g. 7000",
                        keyboardType = KeyboardType.Number)
                }
            }
        }

        // Fuel Order field
        Column {
            Row(verticalAlignment = Alignment.CenterVertically) {
                FieldLabel("Fuel Order (lbs)")
                if (isAutoCalc) {
                    Spacer(Modifier.width(8.dp))
                    Text("← calculated", fontSize = 11.sp, color = colors.accent, fontWeight = FontWeight.Normal)
                }
            }
            OutlinedTextField(
                value = fuelInput,
                onValueChange = { fuelInput = it; fuelManual = true },
                placeholder = { Text("e.g. 5000", fontSize = 14.sp, color = colors.textMuted) },
                modifier = Modifier.fillMaxWidth(),
                singleLine = true,
                shape = RoundedCornerShape(8.dp),
                keyboardOptions = androidx.compose.foundation.text.KeyboardOptions(
                    keyboardType = KeyboardType.Number
                ),
                colors = OutlinedTextFieldDefaults.colors(
                    focusedBorderColor = if (isAutoCalc) colors.accent else colors.accent,
                    unfocusedBorderColor = if (isAutoCalc) colors.accent.copy(alpha = 0.5f) else colors.border,
                    focusedTextColor = colors.text, unfocusedTextColor = colors.text,
                    cursorColor = colors.accent,
                    focusedContainerColor = if (isAutoCalc) colors.accent.copy(alpha = 0.05f) else androidx.compose.ui.graphics.Color.Transparent,
                    unfocusedContainerColor = if (isAutoCalc) colors.accent.copy(alpha = 0.05f) else androidx.compose.ui.graphics.Color.Transparent,
                )
            )
        }

        ClearButton(onClick = {
            tempInput = ""; totalInput = ""; onBoardInput = ""
            fuelInput = ""; fuelManual = false
            densityInput = if (densityUnit == "lbgal") "%.2f".format(0.810 * Calculations.LB_PER_GAL_PER_KGL) else "0.810"
        })

        // Results
        if (results != null) {
            data class VolumeRow(val key: String, val label: String, val value: Int)
            val allVolumes = listOf(
                VolumeRow("usgal", "US Gallons", results.usGal),
                VolumeRow("liters", "Liters", results.liters),
                VolumeRow("impgal", "Imperial Gallons", results.impGal),
            )
            val primary = allVolumes.find { it.key == volumeUnit } ?: allVolumes[0]
            val secondary = allVolumes.filter { it.key != volumeUnit }

            ResultCard {
                Text("ORDER QUANTITIES (ROUNDED UP TO NEAREST 10)", fontSize = 11.sp,
                    fontWeight = FontWeight.Bold, color = colors.textMuted, letterSpacing = 0.5.sp)
                Spacer(Modifier.height(14.dp))

                ResultRow(label = primary.label, value = "%,d".format(primary.value))
                secondary.forEach { vol ->
                    Row(Modifier.fillMaxWidth().padding(vertical = 4.dp),
                        horizontalArrangement = Arrangement.SpaceBetween,
                        verticalAlignment = Alignment.CenterVertically) {
                        Text(vol.label, fontSize = 14.sp, fontWeight = FontWeight.Medium,
                            color = colors.textSecondary.copy(alpha = 0.65f))
                        Text("%,d".format(vol.value), fontSize = 20.sp, fontWeight = FontWeight.Bold,
                            color = colors.accent.copy(alpha = 0.65f), fontFamily = FontFamily.Monospace)
                    }
                }

                // Density footer
                ResultDivider()
                Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceBetween,
                    verticalAlignment = Alignment.CenterVertically) {
                    Text("Reference density (15°C)", fontSize = 12.sp, color = colors.textMuted)
                    Text("${results.refDensityLbGal} lb/gal", fontSize = 13.sp, color = colors.textMuted,
                        fontFamily = FontFamily.Monospace)
                }
                Spacer(Modifier.height(4.dp))
                Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceBetween,
                    verticalAlignment = Alignment.CenterVertically) {
                    Text("Corrected density (${results.tempCDisplay}°C)", fontSize = 12.sp, color = colors.accent)
                    Text("${results.correctedLbGal} lb/gal", fontSize = 13.sp, fontWeight = FontWeight.SemiBold,
                        color = colors.accent, fontFamily = FontFamily.Monospace)
                }
            }
        }
    }
}
