package com.harshmallow.pilottoolkit.ui

import android.content.Context
import androidx.activity.compose.rememberLauncherForActivityResult
import androidx.activity.result.contract.ActivityResultContracts
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Check
import androidx.compose.material.icons.filled.Menu
import androidx.compose.material.icons.filled.Close
import androidx.compose.material.icons.filled.Delete
import androidx.compose.material.icons.filled.Share
import androidx.compose.material3.*
import androidx.compose.material3.TabRowDefaults.tabIndicatorOffset
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.platform.LocalContext
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.harshmallow.pilottoolkit.data.*
import com.harshmallow.pilottoolkit.ui.modules.*
import com.harshmallow.pilottoolkit.ui.theme.ToolkitTheme
import kotlinx.coroutines.delay

enum class Module(val label: String, val title: String, val subtitle: String) {
    PASSDOWN("Passdown", "Passdown", "Crew passdown · Maintenance status · History"),
    FUEL("Fuel", "Fuel Order Calculator", "ASTM D1250 Table 6B density correction · Quantities rounded up to nearest 10"),
    PAVEMENT("Pavement", "Pavement Strength / ESWL", "PCN/PCR · ESWL · Pavement classification"),
    CROSSWIND("Crosswind", "Crosswind Calculator", "Headwind, tailwind, and crosswind components"),
    BUCKETS("Buckets", "Fuel Buckets", "Stage length vs. fuel burn schedule"),
    FL("FL / m", "Flight Level ↔ Meters", "ICAO conversion table · China RVSM FLAS"),
    HF("HF Freq", "HF Frequencies", "Active ARINC HF assignments · Atlantic & Pacific"),
    REST("Crew Rest", "Crew Rest", "Augmented operations · Sequential rest rotation"),
}

private const val PREFS_NAME = "pilot_toolkit_prefs"
private const val KEY_DEFAULT_AIRCRAFT = "default_aircraft"
private const val KEY_DARK_MODE = "dark_mode"

private fun getPrefs(context: Context) = context.getSharedPreferences(PREFS_NAME, Context.MODE_PRIVATE)
fun getSavedDefaultAircraft(context: Context): String = getPrefs(context).getString(KEY_DEFAULT_AIRCRAFT, "G450") ?: "G450"
fun saveDefaultAircraft(context: Context, id: String) = getPrefs(context).edit().putString(KEY_DEFAULT_AIRCRAFT, id).apply()
fun getSavedDarkMode(context: Context): Boolean = getPrefs(context).getBoolean(KEY_DARK_MODE, false)
fun saveDarkMode(context: Context, value: Boolean) = getPrefs(context).edit().putBoolean(KEY_DARK_MODE, value).apply()

private const val KEY_VOLUME_UNIT = "volume_unit"
fun detectDefaultVolumeUnit(): String {
    val locale = java.util.Locale.getDefault()
    val country = locale.country.uppercase()
    return when {
        country == "US" || country == "PR" || country == "VI" || country == "GU" -> "usgal"
        country == "GB" || country == "LC" || country == "AG" || country == "KY"
            || country == "BZ" || country == "MS" || country == "VG" || country == "AI" -> "impgal"
        else -> "liters"
    }
}
fun getSavedVolumeUnit(context: Context): String {
    val saved = getPrefs(context).getString(KEY_VOLUME_UNIT, null)
    return if (saved != null && saved in listOf("usgal", "liters", "impgal")) saved else detectDefaultVolumeUnit()
}
fun saveVolumeUnit(context: Context, unit: String) = getPrefs(context).edit().putString(KEY_VOLUME_UNIT, unit).apply()

@Composable
fun PilotToolkitApp(darkMode: Boolean, onToggleDarkMode: () -> Unit, importUri: android.net.Uri? = null, onImportConsumed: () -> Unit = {}) {
    val colors = ToolkitTheme.colors
    val context = LocalContext.current

    var selectedAircraftId by remember { mutableStateOf(getSavedDefaultAircraft(context)) }
    var defaultAircraftId by remember { mutableStateOf(getSavedDefaultAircraft(context)) }
    var activeModule by remember { mutableStateOf(Module.FUEL) }
    var showDefaultConfirm by remember { mutableStateOf(false) }
    var menuOpen by remember { mutableStateOf(false) }
    var profilesMap by remember { mutableStateOf(getAllFuelProfiles(context)) }
    var profileImportStatus by remember { mutableStateOf<Pair<String, String>?>(null) }
    var volumeUnit by remember { mutableStateOf(getSavedVolumeUnit(context)) }

    // File picker for CSV import
    val csvImportLauncher = rememberLauncherForActivityResult(
        contract = ActivityResultContracts.GetContent()
    ) { uri ->
        if (uri == null) return@rememberLauncherForActivityResult
        try {
            val text = context.contentResolver.openInputStream(uri)?.bufferedReader()?.readText()
                ?: throw Exception("Cannot read file")
            val (buckets, error) = parseBucketCSV(text)
            if (error != null) {
                profileImportStatus = "error" to error
            } else if (buckets != null) {
                // Use filename as default name
                val cursor = context.contentResolver.query(uri, null, null, null, null)
                val fileName = cursor?.use { c ->
                    if (c.moveToFirst()) c.getString(c.getColumnIndexOrThrow(android.provider.OpenableColumns.DISPLAY_NAME))
                    else null
                }?.replace(Regex("\\.[^.]+$"), "")?.replace(Regex("[_-]"), " ")?.trim() ?: "Custom"
                // For now use filename directly — Android doesn't have prompt() so we use the filename
                saveFuelProfile(context, selectedAircraftId, fileName, buckets)
                profilesMap = getAllFuelProfiles(context)
                profileImportStatus = "success" to "Imported \"$fileName\" (${buckets.size} entries) for ${getAircraftById(selectedAircraftId).label}."
            }
        } catch (e: Exception) {
            profileImportStatus = "error" to "Import failed: ${e.message}"
        }
    }

    // File picker for JSON profile import
    val jsonImportLauncher = rememberLauncherForActivityResult(
        contract = ActivityResultContracts.GetContent()
    ) { uri ->
        if (uri == null) return@rememberLauncherForActivityResult
        try {
            val text = context.contentResolver.openInputStream(uri)?.bufferedReader()?.readText()
                ?: throw Exception("Cannot read file")
            val (name, aircraft, buckets) = parseFuelProfileJSON(text)
            val targetAircraft = aircraft.ifEmpty { selectedAircraftId }
            saveFuelProfile(context, targetAircraft, name, buckets)
            profilesMap = getAllFuelProfiles(context)
            profileImportStatus = "success" to "Imported \"$name\" (${buckets.size} entries) for ${getAircraftById(targetAircraft).label}."
        } catch (e: Exception) {
            profileImportStatus = "error" to "Import failed: ${e.message}"
        }
    }

    LaunchedEffect(profileImportStatus) {
        if (profileImportStatus != null) { delay(4000); profileImportStatus = null }
    }

    // Auto-switch to Passdown tab when import URI arrives
    LaunchedEffect(importUri) {
        if (importUri != null) activeModule = Module.PASSDOWN
    }

    val isDefault = selectedAircraftId == defaultAircraftId
    val selectedAircraft = getAircraftById(selectedAircraftId)

    // Purge old passdowns on launch
    LaunchedEffect(Unit) {
        val months = getRetentionMonths(context)
        if (months > 0) purgeOldPassdowns(context, months)
    }

    LaunchedEffect(showDefaultConfirm) {
        if (showDefaultConfirm) { delay(2000); showDefaultConfirm = false }
    }

    Box(Modifier.fillMaxSize()) {
        Column(Modifier.fillMaxSize().background(colors.bg)) {
            /* ── Top Bar ── */
            Row(
                Modifier.fillMaxWidth().background(colors.navBg).padding(horizontal = 16.dp, vertical = 12.dp),
                horizontalArrangement = Arrangement.SpaceBetween, verticalAlignment = Alignment.CenterVertically
            ) {
                Row(verticalAlignment = Alignment.CenterVertically) {
                    Box(Modifier.size(8.dp).clip(CircleShape).background(colors.accent))
                    Spacer(Modifier.width(10.dp))
                    Text("PILOT'S TOOLKIT", fontSize = 14.sp, fontWeight = FontWeight.Bold,
                        color = Color.White, letterSpacing = 0.5.sp)
                    Spacer(Modifier.width(8.dp))
                    Text("ALPHA", fontSize = 10.sp, fontWeight = FontWeight.SemiBold, color = colors.accent,
                        modifier = Modifier.clip(RoundedCornerShape(4.dp))
                            .background(colors.accent.copy(alpha = 0.15f)).padding(horizontal = 8.dp, vertical = 2.dp))
                }
                Row(verticalAlignment = Alignment.CenterVertically) {
                    // Compact aircraft indicator
                    Box(modifier = Modifier.clip(RoundedCornerShape(4.dp))
                        .background(Color.White.copy(alpha = 0.1f))
                        .clickable { menuOpen = true }
                        .padding(horizontal = 10.dp, vertical = 4.dp)) {
                        Text(selectedAircraft.label, fontSize = 12.sp,
                            fontWeight = if (isDefault) FontWeight.Bold else FontWeight.SemiBold,
                            color = if (isDefault) colors.accent else colors.warning,
                            letterSpacing = 0.5.sp)
                    }
                    Spacer(Modifier.width(4.dp))
                    IconButton(onClick = { menuOpen = true }) {
                        Icon(Icons.Default.Menu, "Menu", tint = Color.White)
                    }
                }
            }

            /* ── Tabs ── */
            ScrollableTabRow(
                selectedTabIndex = Module.entries.indexOf(activeModule),
                containerColor = colors.surface, contentColor = colors.accent,
                edgePadding = 8.dp, divider = { HorizontalDivider(color = colors.border) },
                indicator = { tabPositions ->
                    val idx = Module.entries.indexOf(activeModule)
                    if (idx < tabPositions.size) {
                        TabRowDefaults.SecondaryIndicator(
                            Modifier.tabIndicatorOffset(tabPositions[idx]), height = 2.5.dp, color = colors.accent
                        )
                    }
                }
            ) {
                Module.entries.forEach { mod ->
                    val isActive = mod == activeModule
                    Tab(selected = isActive, onClick = { activeModule = mod },
                        text = {
                            Text(mod.label, fontWeight = if (isActive) FontWeight.Bold else FontWeight.Medium,
                                fontSize = 13.sp, color = if (isActive) colors.accent else colors.textMuted)
                        })
                }
            }

            /* ── Content ── */
            Column(
                Modifier.fillMaxSize().verticalScroll(rememberScrollState()).padding(20.dp),
                horizontalAlignment = Alignment.CenterHorizontally
            ) {
                Card(
                    modifier = Modifier.widthIn(max = if (activeModule == Module.PASSDOWN) 540.dp else 460.dp).fillMaxWidth(),
                    shape = RoundedCornerShape(12.dp),
                    colors = CardDefaults.cardColors(containerColor = colors.surface),
                    elevation = CardDefaults.cardElevation(defaultElevation = 2.dp),
                    border = androidx.compose.foundation.BorderStroke(1.dp, colors.border)
                ) {
                    Column(Modifier.padding(24.dp)) {
                        Text(activeModule.title, fontSize = 18.sp, fontWeight = FontWeight.Bold, color = colors.text)
                        Spacer(Modifier.height(4.dp))
                        Text(activeModule.subtitle, fontSize = 13.sp, color = colors.textMuted, lineHeight = 18.sp)
                        Spacer(Modifier.height(20.dp))
                        HorizontalDivider(color = colors.border)
                        Spacer(Modifier.height(20.dp))

                        when (activeModule) {
                            Module.PASSDOWN -> PassdownModule(
                                importUri = importUri,
                                onImportConsumed = onImportConsumed
                            )
                            Module.FUEL -> FuelOrderModule(volumeUnit = volumeUnit)
                            Module.PAVEMENT -> PavementModule(aircraft = selectedAircraft)
                            Module.CROSSWIND -> CrosswindModule()
                            Module.BUCKETS -> FuelBucketsModule(
                                aircraft = selectedAircraft,
                                fuelProfile = profilesMap[selectedAircraftId]
                            )
                            Module.FL -> FlightLevelModule()
                            Module.HF -> HFModule()
                            Module.REST -> CrewRestModule()
                        }
                    }
                }
                Spacer(Modifier.height(24.dp))
                Text("Not for operational use · Verify all calculations independently",
                    fontSize = 11.sp, color = colors.textMuted, letterSpacing = 0.3.sp)
                Spacer(Modifier.height(16.dp))
            }
        }

        /* ── Hamburger Menu Overlay ── */
        if (menuOpen) {
            Box(Modifier.fillMaxSize().background(Color.Black.copy(alpha = 0.5f)).clickable { menuOpen = false })
            Box(Modifier.fillMaxHeight().width(280.dp).align(Alignment.TopEnd).background(colors.surface)) {
                Column(Modifier.padding(24.dp).verticalScroll(rememberScrollState())) {
                    Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceBetween,
                        verticalAlignment = Alignment.CenterVertically) {
                        Text("Settings", fontSize = 16.sp, fontWeight = FontWeight.Bold, color = colors.text)
                        IconButton(onClick = { menuOpen = false }) {
                            Icon(Icons.Default.Close, "Close", tint = colors.textMuted)
                        }
                    }
                    Spacer(Modifier.height(20.dp))

                    // Aircraft selector
                    Text("AIRCRAFT", fontSize = 11.sp, fontWeight = FontWeight.Bold,
                        color = colors.textMuted, letterSpacing = 0.5.sp)
                    Spacer(Modifier.height(10.dp))
                    aircraftRegistry.forEach { ac ->
                        val isSelected = ac.id == selectedAircraftId
                        Row(
                            Modifier.fillMaxWidth()
                                .clip(RoundedCornerShape(6.dp))
                                .background(if (isSelected) colors.accent.copy(alpha = 0.1f) else Color.Transparent)
                                .clickable { selectedAircraftId = ac.id }
                                .padding(horizontal = 12.dp, vertical = 10.dp),
                            horizontalArrangement = Arrangement.SpaceBetween,
                            verticalAlignment = Alignment.CenterVertically
                        ) {
                            Text(ac.label, fontSize = 14.sp,
                                fontWeight = if (isSelected) FontWeight.Bold else FontWeight.Medium,
                                color = if (isSelected) colors.accent else colors.text)
                            if (isSelected && isDefault) {
                                Text("DEFAULT", fontSize = 10.sp, fontWeight = FontWeight.Bold,
                                    color = colors.accent.copy(alpha = 0.6f), letterSpacing = 0.3.sp)
                            }
                        }
                    }
                    Spacer(Modifier.height(8.dp))
                    if (!isDefault) {
                        TextButton(
                            onClick = {
                                saveDefaultAircraft(context, selectedAircraftId)
                                defaultAircraftId = selectedAircraftId; showDefaultConfirm = true
                            },
                            modifier = Modifier.fillMaxWidth()
                        ) {
                            Text("Set ${selectedAircraft.label} as Default", fontSize = 12.sp,
                                fontWeight = FontWeight.SemiBold, color = colors.accent)
                        }
                    }
                    if (showDefaultConfirm) {
                        Text("✓ Default saved", fontSize = 12.sp, fontWeight = FontWeight.SemiBold,
                            color = colors.accent, modifier = Modifier.padding(start = 12.dp, top = 4.dp))
                    }

                    Spacer(Modifier.height(16.dp))
                    HorizontalDivider(color = colors.border)
                    Spacer(Modifier.height(16.dp))

                    // Dark mode
                    Row(Modifier.fillMaxWidth().clickable { onToggleDarkMode() }.padding(vertical = 12.dp),
                        horizontalArrangement = Arrangement.SpaceBetween, verticalAlignment = Alignment.CenterVertically) {
                        Text("Dark Mode", fontSize = 14.sp, color = colors.text)
                        Text(if (darkMode) "☀" else "🌙", fontSize = 16.sp)
                    }
                    HorizontalDivider(color = colors.border)
                    Spacer(Modifier.height(16.dp))

                    // Volume Unit Preference
                    Text("PRIMARY VOLUME UNIT", fontSize = 11.sp, fontWeight = FontWeight.Bold,
                        color = colors.textMuted, letterSpacing = 0.5.sp)
                    Spacer(Modifier.height(10.dp))
                    Row(Modifier.fillMaxWidth().clip(RoundedCornerShape(6.dp))
                        .border(1.dp, colors.border, RoundedCornerShape(6.dp))) {
                        listOf("usgal" to "US Gal", "liters" to "Liters", "impgal" to "Imp Gal").forEach { (key, label) ->
                            val active = volumeUnit == key
                            Box(
                                Modifier.weight(1f)
                                    .background(if (active) colors.accent else Color.Transparent)
                                    .clickable { volumeUnit = key; saveVolumeUnit(context, key) }
                                    .padding(vertical = 10.dp),
                                contentAlignment = Alignment.Center
                            ) {
                                Text(label, fontSize = 12.sp, fontWeight = FontWeight.SemiBold,
                                    color = if (active) Color.White else colors.textSecondary)
                            }
                        }
                    }
                    Text("Shown first in fuel order results", fontSize = 11.sp, color = colors.textMuted,
                        modifier = Modifier.padding(start = 12.dp, top = 4.dp))
                    Spacer(Modifier.height(16.dp))
                    HorizontalDivider(color = colors.border)
                    Spacer(Modifier.height(16.dp))

                    // Passdown Retention
                    Text("PASSDOWN RETENTION", fontSize = 11.sp, fontWeight = FontWeight.Bold,
                        color = colors.textMuted, letterSpacing = 0.5.sp)
                    Spacer(Modifier.height(10.dp))
                    var retentionMonths by remember { mutableStateOf(getRetentionMonths(context)) }
                    val retentionOptions = listOf(3 to "3 months", 6 to "6 months", 12 to "12 months",
                        24 to "24 months", 36 to "36 months", 0 to "Never delete")
                    retentionOptions.forEach { (months, label) ->
                        Row(
                            Modifier.fillMaxWidth()
                                .clip(RoundedCornerShape(6.dp))
                                .background(if (retentionMonths == months) colors.accent.copy(alpha = 0.1f) else Color.Transparent)
                                .clickable { retentionMonths = months; saveRetentionMonths(context, months) }
                                .padding(horizontal = 12.dp, vertical = 8.dp),
                            verticalAlignment = Alignment.CenterVertically
                        ) {
                            Text(label, fontSize = 13.sp,
                                fontWeight = if (retentionMonths == months) FontWeight.Bold else FontWeight.Normal,
                                color = if (retentionMonths == months) colors.accent else colors.text)
                        }
                    }
                    Text("Auto-purge on app open", fontSize = 11.sp, color = colors.textMuted,
                        modifier = Modifier.padding(start = 12.dp, top = 4.dp))

                    Spacer(Modifier.height(16.dp))
                    HorizontalDivider(color = colors.border)
                    Spacer(Modifier.height(16.dp))

                    // Fuel Profiles
                    Text("FUEL DATA", fontSize = 11.sp, fontWeight = FontWeight.Bold,
                        color = colors.textMuted, letterSpacing = 0.5.sp)
                    Spacer(Modifier.height(10.dp))

                    // Import CSV button
                    OutlinedButton(
                        onClick = { csvImportLauncher.launch("*/*") },
                        modifier = Modifier.fillMaxWidth(),
                        shape = RoundedCornerShape(8.dp),
                        border = androidx.compose.foundation.BorderStroke(1.dp, colors.border)
                    ) {
                        Column(Modifier.fillMaxWidth()) {
                            Text("Import CSV for ${selectedAircraft.label}", fontSize = 13.sp,
                                fontWeight = FontWeight.Medium, color = colors.text)
                            Text("Two columns: stage_length, fuel_burn", fontSize = 11.sp, color = colors.textMuted)
                        }
                    }
                    Spacer(Modifier.height(6.dp))

                    // Import JSON profile button
                    OutlinedButton(
                        onClick = { jsonImportLauncher.launch("*/*") },
                        modifier = Modifier.fillMaxWidth(),
                        shape = RoundedCornerShape(8.dp),
                        border = androidx.compose.foundation.BorderStroke(1.dp, colors.border)
                    ) {
                        Column(Modifier.fillMaxWidth()) {
                            Text("Import Fuel Profile (.json)", fontSize = 13.sp,
                                fontWeight = FontWeight.Medium, color = colors.text)
                            Text("Shared profile from another device or crew member", fontSize = 11.sp, color = colors.textMuted)
                        }
                    }

                    // Loaded profiles list
                    if (profilesMap.isNotEmpty()) {
                        Spacer(Modifier.height(10.dp))
                        Text("Loaded profiles:", fontSize = 11.sp, color = colors.textMuted)
                        Spacer(Modifier.height(6.dp))
                        profilesMap.forEach { (acId, profile) ->
                            Row(
                                Modifier.fillMaxWidth()
                                    .clip(RoundedCornerShape(6.dp))
                                    .background(colors.surfaceAlt)
                                    .padding(horizontal = 12.dp, vertical = 8.dp),
                                horizontalArrangement = Arrangement.SpaceBetween,
                                verticalAlignment = Alignment.CenterVertically
                            ) {
                                Column(Modifier.weight(1f)) {
                                    Text(profile.name, fontSize = 12.sp, fontWeight = FontWeight.SemiBold, color = colors.text)
                                    Text("${getAircraftById(acId).label} · ${profile.buckets.size} entries",
                                        fontSize = 11.sp, color = colors.textMuted)
                                }
                                Row {
                                    IconButton(
                                        onClick = { exportFuelProfileJSON(context, acId, profile) },
                                        modifier = Modifier.size(32.dp)
                                    ) {
                                        Icon(Icons.Default.Share, "Export", tint = colors.textMuted,
                                            modifier = Modifier.size(16.dp))
                                    }
                                    IconButton(
                                        onClick = {
                                            clearFuelProfile(context, acId)
                                            profilesMap = getAllFuelProfiles(context)
                                            profileImportStatus = "success" to "Cleared profile for ${getAircraftById(acId).label}."
                                        },
                                        modifier = Modifier.size(32.dp)
                                    ) {
                                        Icon(Icons.Default.Delete, "Clear", tint = colors.textMuted,
                                            modifier = Modifier.size(16.dp))
                                    }
                                }
                            }
                            Spacer(Modifier.height(4.dp))
                        }
                    }

                    // Import status
                    if (profileImportStatus != null) {
                        Spacer(Modifier.height(8.dp))
                        Box(
                            Modifier.fillMaxWidth().clip(RoundedCornerShape(6.dp))
                                .background(
                                    if (profileImportStatus!!.first == "error") colors.dangerBg
                                    else colors.accent.copy(alpha = 0.1f)
                                )
                                .border(
                                    1.dp,
                                    if (profileImportStatus!!.first == "error") colors.dangerBorder
                                    else colors.accent.copy(alpha = 0.25f),
                                    RoundedCornerShape(6.dp)
                                )
                                .padding(8.dp)
                        ) {
                            Text(
                                profileImportStatus!!.second, fontSize = 12.sp, fontWeight = FontWeight.SemiBold,
                                color = if (profileImportStatus!!.first == "error") colors.danger else colors.accent
                            )
                        }
                    }

                    Spacer(Modifier.height(16.dp))
                    HorizontalDivider(color = colors.border)
                    Spacer(Modifier.height(16.dp))
                    Text("About", fontSize = 11.sp, fontWeight = FontWeight.Bold, color = colors.textMuted, letterSpacing = 0.5.sp)
                    Spacer(Modifier.height(8.dp))
                    Text("Pilot's Toolkit v0.1.0 alpha", fontSize = 13.sp, color = colors.textSecondary)
                }
            }
        }
    }
}
