package com.harshmallow.pilottoolkit.ui.modules

import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.foundation.BorderStroke
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.unit.dp
import androidx.compose.ui.unit.sp
import com.harshmallow.pilottoolkit.data.*
import com.harshmallow.pilottoolkit.ui.components.*
import com.harshmallow.pilottoolkit.ui.theme.ToolkitTheme

private val eastColor = Color(0xFF4DABF7)
private val westColor = Color(0xFFF59F00)

@Composable
fun FlightLevelModule() {
    val colors = ToolkitTheme.colors
    var mode by remember { mutableStateOf("flas") }
    var searchInput by remember { mutableStateOf("") }
    var searchUnit by remember { mutableStateOf("meters") }

    Column {
        // Mode selector
        Row(
            Modifier.fillMaxWidth()
                .clip(RoundedCornerShape(6.dp))
        ) {
            listOf("flas" to "China FLAS", "lookup" to "Meters ↔ Feet").forEach { (key, label) ->
                val active = mode == key
                Box(
                    Modifier
                        .weight(1f)
                        .background(if (active) colors.accent else colors.surfaceAlt)
                        .clickable { mode = key }
                        .padding(vertical = 12.dp),
                    contentAlignment = Alignment.Center
                ) {
                    Text(label, fontSize = 13.sp, fontWeight = FontWeight.SemiBold,
                        color = if (active) Color.White else colors.textSecondary)
                }
            }
        }

        Spacer(Modifier.height(16.dp))

        if (mode == "lookup") {
            LookupMode(searchInput, { searchInput = it }, searchUnit, { searchUnit = it })
        } else {
            FLASMode()
        }
    }
}

@Composable
private fun LookupMode(
    searchInput: String, onSearchChange: (String) -> Unit,
    searchUnit: String, onUnitChange: (String) -> Unit
) {
    val colors = ToolkitTheme.colors
    val searchVal = searchInput.trim().toIntOrNull()
    val filtered = remember(searchInput, searchUnit) {
        if (searchVal == null || searchVal < 0) metersToFeetTable
        else metersToFeetTable.filter {
            val target = if (searchUnit == "meters") it.meters else it.feet
            target.toString().startsWith(searchInput.trim())
        }
    }
    val exactMatch = remember(searchVal, searchUnit) {
        if (searchVal == null) null
        else metersToFeetTable.find {
            if (searchUnit == "meters") it.meters == searchVal else it.feet == searchVal
        }
    }

    // Search bar
    Row(
        Modifier.fillMaxWidth(),
        verticalAlignment = Alignment.CenterVertically,
        horizontalArrangement = Arrangement.spacedBy(8.dp)
    ) {
        OutlinedTextField(
            value = searchInput, onValueChange = onSearchChange,
            placeholder = {
                Text(
                    if (searchUnit == "meters") "Type meters..." else "Type feet...",
                    fontSize = 14.sp, color = colors.textMuted
                )
            },
            keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number),
            modifier = Modifier.weight(1f),
            singleLine = true,
            textStyle = LocalTextStyle.current.copy(fontFamily = FontFamily.Monospace, fontSize = 16.sp)
        )
        Row(Modifier.clip(RoundedCornerShape(6.dp))) {
            listOf("meters" to "m", "feet" to "ft").forEach { (key, label) ->
                val active = searchUnit == key
                Box(
                    Modifier
                        .background(if (active) colors.accent else colors.surfaceAlt)
                        .clickable { onUnitChange(key); onSearchChange("") }
                        .padding(horizontal = 14.dp, vertical = 12.dp),
                    contentAlignment = Alignment.Center
                ) {
                    Text(label, fontSize = 12.sp, fontWeight = FontWeight.Bold,
                        color = if (active) Color.White else colors.textSecondary)
                }
            }
        }
    }

    // Exact match callout
    if (exactMatch != null) {
        Spacer(Modifier.height(12.dp))
        ResultCard {
            Row(
                Modifier.fillMaxWidth(),
                horizontalArrangement = Arrangement.SpaceBetween,
                verticalAlignment = Alignment.CenterVertically
            ) {
                Text("${"%,d".format(exactMatch.meters)} m", fontSize = 14.sp, color = colors.textSecondary)
                Text("${"%,d".format(exactMatch.feet)} ft", fontSize = 24.sp, fontWeight = FontWeight.Bold,
                    color = colors.accent, fontFamily = FontFamily.Monospace)
            }
        }
    }

    Spacer(Modifier.height(12.dp))

    // Table
    Card(
        modifier = Modifier.fillMaxWidth().height(350.dp),
        shape = RoundedCornerShape(8.dp),
        colors = CardDefaults.cardColors(containerColor = colors.surface),
        border = BorderStroke(1.dp, colors.border)
    ) {
        LazyColumn {
            item {
                Row(
                    Modifier.fillMaxWidth().background(colors.surfaceAlt)
                        .padding(horizontal = 16.dp, vertical = 10.dp)
                ) {
                    Text("METERS", Modifier.weight(1f), fontSize = 11.sp, fontWeight = FontWeight.Bold,
                        color = colors.textMuted, letterSpacing = 0.5.sp)
                    Text("FEET", fontSize = 11.sp, fontWeight = FontWeight.Bold,
                        color = colors.textMuted, letterSpacing = 0.5.sp)
                }
                HorizontalDivider(color = colors.border, thickness = 2.dp)
            }
            items(filtered) { entry ->
                val isExact = exactMatch != null && entry.meters == exactMatch.meters
                Row(
                    Modifier.fillMaxWidth()
                        .background(if (isExact) colors.accent.copy(alpha = 0.1f) else Color.Transparent)
                        .padding(horizontal = 16.dp, vertical = 6.dp)
                ) {
                    Text(
                        "%,d".format(entry.meters), Modifier.weight(1f), fontSize = 13.sp,
                        fontFamily = FontFamily.Monospace,
                        fontWeight = if (isExact) FontWeight.Bold else FontWeight.Normal,
                        color = if (isExact) colors.accent else colors.text
                    )
                    Text(
                        "%,d".format(entry.feet), fontSize = 13.sp,
                        fontFamily = FontFamily.Monospace,
                        fontWeight = if (isExact) FontWeight.Bold else FontWeight.Normal,
                        color = if (isExact) colors.accent else colors.text
                    )
                }
                HorizontalDivider(color = colors.border)
            }
        }
    }

    Spacer(Modifier.height(8.dp))
    Text(
        "GVIII-G700 Operating Manual Table 15. Values rounded to nearest 100 ft.\nDo not use for approach minima.",
        fontSize = 11.sp, color = colors.textMuted, lineHeight = 16.sp
    )
}

@Composable
private fun FLASMode() {
    val colors = ToolkitTheme.colors
    var eastSelected by remember { mutableStateOf(true) }
    var westSelected by remember { mutableStateOf(true) }

    // If user deselects both, treat as both selected
    val showEast = eastSelected || !westSelected
    val showWest = westSelected || !eastSelected

    val filtered = remember(showEast, showWest) {
        if (showEast && showWest) chinaFLAS
        else chinaFLAS.filter { entry ->
            val isEast = entry.feet in chinaRVSMEastbound
            val isWest = entry.feet in chinaRVSMWestbound
            when {
                isEast -> showEast
                isWest -> showWest
                else -> true // non-RVSM levels always shown
            }
        }
    }

    // Direction toggle buttons
    Row(
        Modifier.fillMaxWidth(),
        horizontalArrangement = Arrangement.spacedBy(8.dp)
    ) {
        // Eastbound button
        Box(
            Modifier
                .weight(1f)
                .clip(RoundedCornerShape(6.dp))
                .background(if (eastSelected) eastColor.copy(alpha = 0.15f) else colors.surfaceAlt)
                .clickable {
                    eastSelected = !eastSelected
                    // If turning off would leave both off, turn on the other
                    if (!eastSelected && !westSelected) westSelected = true
                }
                .padding(vertical = 10.dp),
            contentAlignment = Alignment.Center
        ) {
            Text(
                "Eastbound 0°–179°", fontSize = 12.sp, fontWeight = FontWeight.SemiBold,
                color = if (eastSelected) eastColor else colors.textMuted
            )
        }
        // Westbound button
        Box(
            Modifier
                .weight(1f)
                .clip(RoundedCornerShape(6.dp))
                .background(if (westSelected) westColor.copy(alpha = 0.15f) else colors.surfaceAlt)
                .clickable {
                    westSelected = !westSelected
                    if (!eastSelected && !westSelected) eastSelected = true
                }
                .padding(vertical = 10.dp),
            contentAlignment = Alignment.Center
        ) {
            Text(
                "Westbound 186°–359°", fontSize = 12.sp, fontWeight = FontWeight.SemiBold,
                color = if (westSelected) westColor else colors.textMuted
            )
        }
    }

    Spacer(Modifier.height(12.dp))

    // FLAS Table
    Card(
        modifier = Modifier.fillMaxWidth().height(400.dp),
        shape = RoundedCornerShape(8.dp),
        colors = CardDefaults.cardColors(containerColor = colors.surface),
        border = BorderStroke(1.dp, colors.border)
    ) {
        LazyColumn {
            item {
                Row(
                    Modifier.fillMaxWidth().background(colors.surfaceAlt)
                        .padding(horizontal = 16.dp, vertical = 10.dp)
                ) {
                    Text("CLEARED (m)", Modifier.weight(1f), fontSize = 11.sp, fontWeight = FontWeight.Bold,
                        color = colors.textMuted, letterSpacing = 0.5.sp)
                    Text("SET (ft)", Modifier.weight(1f), fontSize = 11.sp, fontWeight = FontWeight.Bold,
                        color = colors.textMuted, letterSpacing = 0.5.sp)
                    Text("RVSM", fontSize = 11.sp, fontWeight = FontWeight.Bold,
                        color = colors.textMuted, letterSpacing = 0.5.sp)
                }
                HorizontalDivider(color = colors.border, thickness = 2.dp)
            }
            items(filtered) { entry ->
                val isEast = entry.feet in chinaRVSMEastbound
                val isWest = entry.feet in chinaRVSMWestbound
                val isRVSM = isEast || isWest
                val rowColor = when {
                    isEast -> eastColor
                    isWest -> westColor
                    else -> colors.text
                }
                val rowBg = when {
                    isEast -> eastColor.copy(alpha = 0.08f)
                    isWest -> westColor.copy(alpha = 0.08f)
                    else -> Color.Transparent
                }
                Row(
                    Modifier.fillMaxWidth()
                        .background(rowBg)
                        .padding(horizontal = 16.dp, vertical = 6.dp),
                    verticalAlignment = Alignment.CenterVertically
                ) {
                    Text(
                        "%,d".format(entry.meters), Modifier.weight(1f), fontSize = 13.sp,
                        fontFamily = FontFamily.Monospace,
                        fontWeight = if (isRVSM) FontWeight.Bold else FontWeight.Normal,
                        color = rowColor
                    )
                    Text(
                        "%,d".format(entry.feet), Modifier.weight(1f), fontSize = 13.sp,
                        fontFamily = FontFamily.Monospace,
                        fontWeight = if (isRVSM) FontWeight.Bold else FontWeight.Normal,
                        color = rowColor
                    )
                    Text(
                        when {
                            isEast -> "E"
                            isWest -> "W"
                            else -> ""
                        },
                        fontSize = 11.sp, fontWeight = FontWeight.Bold, color = rowColor
                    )
                }
                HorizontalDivider(color = colors.border)
            }
        }
    }

    Spacer(Modifier.height(8.dp))

    // Legend
    Row(horizontalArrangement = Arrangement.spacedBy(16.dp)) {
        Text("● E Eastbound 0°–179°", fontSize = 11.sp, color = eastColor, fontWeight = FontWeight.SemiBold)
        Text("● W Westbound 186°–359°", fontSize = 11.sp, color = westColor, fontWeight = FontWeight.SemiBold)
    }
    Spacer(Modifier.height(4.dp))
    Text(
        "ATC clears flight level in meters. Set altimeter to corresponding feet value.\n" +
                "Onboard metric readout may differ from cleared value by up to 30 m due to rounding.\n" +
                "Do not use for approach minima.",
        fontSize = 11.sp, color = colors.textMuted, lineHeight = 16.sp
    )
}
