// Copyright (C) 2026 Jason M. Schwefel. All Rights Reserved.
package com.coldboreballisticsllc.scopedope.ui.screens.settings

import android.content.Intent
import android.net.Uri
import androidx.compose.foundation.clickable
import androidx.compose.foundation.gestures.detectTapGestures
import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.ArrowBack
import androidx.compose.material.icons.automirrored.filled.ArrowForward
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.unit.dp
import androidx.hilt.navigation.compose.hiltViewModel
import com.coldboreballisticsllc.scopedope.BuildConfig
import com.coldboreballisticsllc.scopedope.label.format.LabelFormats
import com.coldboreballisticsllc.scopedope.label.format.LabelShape
import com.coldboreballisticsllc.scopedope.label.format.LabelSizeGroup
import com.coldboreballisticsllc.scopedope.ui.components.InstrumentPanel
import com.coldboreballisticsllc.scopedope.ui.components.SectionDivider
import com.coldboreballisticsllc.scopedope.ui.crash.CrashConsentViewModel
import com.coldboreballisticsllc.scopedope.ui.session.AdjUnit
import com.coldboreballisticsllc.scopedope.ui.session.DistancePreset
import com.coldboreballisticsllc.scopedope.ui.session.MeasureSystem
import com.coldboreballisticsllc.scopedope.ui.session.PrinterViewModel
import com.coldboreballisticsllc.scopedope.ui.session.SessionViewModel
import com.coldboreballisticsllc.scopedope.ui.theme.*

private fun layoutTitle(fmt: com.coldboreballisticsllc.scopedope.label.format.LabelFormat): String {
    val shape = fmt.shape as? LabelShape.Rectangle ?: return ""
    return when {
        shape.widthMm == shape.heightMm ->
            if (fmt.columns == 1) "1 Column" else "${fmt.columns} Columns"
        shape.widthMm < shape.heightMm  ->
            if (fmt.columns == 1) "Portrait" else "Portrait ${fmt.columns} col"
        else                             ->
            "Landscape ${fmt.columns} col"
    }
}

private fun layoutSubtitle(fmt: com.coldboreballisticsllc.scopedope.label.format.LabelFormat): String {
    val shape = fmt.shape as? LabelShape.Rectangle ?: return ""
    val w = shape.widthMm.toInt()
    val h = shape.heightMm.toInt()
    val cols = fmt.columns
    return "$w mm wide × $h mm tall — $cols column${if (cols > 1) "s" else ""}, max ${fmt.maxEntries}"
}

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun SettingsScreen(
    onBack:            () -> Unit,
    onShowTutorial:    () -> Unit = {},
    onShowAdvanced:    () -> Unit = {},
    onShowFeedback:    () -> Unit = {},
    onShowSupport:     () -> Unit = {},
    onResetOnboarding: () -> Unit = {},
    sessionVm:         SessionViewModel = hiltViewModel(),
    printerVm:         PrinterViewModel = hiltViewModel(),
    crashConsentVm:    CrashConsentViewModel = hiltViewModel(),
) {
    val state          by sessionVm.state.collectAsState()
    val printerUiState by printerVm.uiState.collectAsState()
    val crashReportingEnabled by crashConsentVm.enabled.collectAsState()
    val context = LocalContext.current

    Scaffold(
        topBar = {
            TopAppBar(
                title = { Text("Settings", style = MaterialTheme.typography.titleLarge) },
                navigationIcon = {
                    IconButton(onClick = onBack) {
                        Icon(Icons.AutoMirrored.Filled.ArrowBack, contentDescription = "Back")
                    }
                },
                colors = TopAppBarDefaults.topAppBarColors(
                    containerColor    = ColorBackground,
                    titleContentColor = ColorTextPrimary,
                ),
            )
        },
        containerColor = ColorBackground,
    ) { padding ->
        Column(
            modifier = Modifier
                .padding(padding)
                .fillMaxSize()
                .verticalScroll(rememberScrollState())
                .padding(16.dp),
            verticalArrangement = Arrangement.spacedBy(12.dp),
        ) {
            // ── Adjustment units ──────────────────────────────────────────────
            InstrumentPanel(label = "Adjustment Units") {
                AdjUnit.entries.forEach { unit ->
                    Row(
                        modifier          = Modifier
                            .fillMaxWidth()
                            .clickable { sessionVm.setAdjUnit(unit) }
                            .heightIn(min = 68.dp)
                            .padding(vertical = 4.dp),
                        verticalAlignment = Alignment.CenterVertically,
                    ) {
                        RadioButton(
                            selected  = state.adjUnit == unit,
                            onClick   = { sessionVm.setAdjUnit(unit) },
                            colors    = RadioButtonDefaults.colors(selectedColor = ColorAmber),
                        )
                        Spacer(Modifier.width(8.dp))
                        Column {
                            Text(
                                text  = unit.name,
                                style = SettingsBodyStyle,
                                color = ColorTextPrimary,
                            )
                            Text(
                                text  = when (unit) {
                                    AdjUnit.MIL -> "Milliradians — 1 decimal place (e.g. 3.5)"
                                    AdjUnit.MOA -> "MOA — 2 decimal places (e.g. 12.50)"
                                },
                                style = SettingsBodySubStyle,
                                color = ColorTextMuted,
                            )
                        }
                    }
                }

                SectionDivider(Modifier.padding(vertical = 6.dp))

                Text(
                    text  = "Click Value",
                    style = SettingsBodyStyle,
                    color = ColorTextPrimary,
                )
                Text(
                    text  = "Must match your scope's turret denomination",
                    style = SettingsBodySubStyle,
                    color = ColorTextMuted,
                )
                Spacer(Modifier.height(2.dp))

                val milOptions = listOf("0.1_mrad" to "0.1 MRAD  (most common)", "0.05_mrad" to "0.05 MRAD")
                val moaOptions = listOf("0.25_moa" to "0.25 MOA  (most common)", "0.5_moa" to "0.5 MOA", "1_moa" to "1 MOA")
                val clickOptions = if (state.adjUnit == AdjUnit.MIL) milOptions else moaOptions

                clickOptions.forEach { (value, label) ->
                    Row(
                        modifier          = Modifier
                            .fillMaxWidth()
                            .clickable { sessionVm.setClickValue(value) }
                            .padding(vertical = 4.dp),
                        verticalAlignment = Alignment.CenterVertically,
                    ) {
                        RadioButton(
                            selected = state.clickValue == value,
                            onClick  = { sessionVm.setClickValue(value) },
                            colors   = RadioButtonDefaults.colors(selectedColor = ColorAmber),
                        )
                        Spacer(Modifier.width(8.dp))
                        Text(
                            text  = label,
                            style = SettingsBodyStyle,
                            color = ColorTextPrimary,
                        )
                    }
                }
            }

            // ── Output distances ──────────────────────────────────────────────
            InstrumentPanel(label = "Output Distances") {
                listOf(DistancePreset.NRL22, DistancePreset.PRS).forEach { preset ->
                    Row(
                        modifier          = Modifier
                            .fillMaxWidth()
                            .clickable { sessionVm.applyDistancePreset(preset) }
                            .padding(vertical = 4.dp),
                        verticalAlignment = Alignment.CenterVertically,
                    ) {
                        RadioButton(
                            selected = state.distancePreset == preset,
                            onClick  = { sessionVm.applyDistancePreset(preset) },
                            colors   = RadioButtonDefaults.colors(selectedColor = ColorAmber),
                        )
                        Spacer(Modifier.width(8.dp))
                        Column {
                            Text(
                                text  = preset.label,
                                style = SettingsBodyStyle,
                                color = ColorTextPrimary,
                            )
                            Text(
                                text  = if (state.measureSystem == MeasureSystem.METRIC) when (preset) {
                                    DistancePreset.NRL22  -> "Short range — 23, 46, 69, 91 m"
                                    DistancePreset.PRS    -> "Extended range — 183–914 m"
                                    DistancePreset.CUSTOM -> preset.description
                                } else preset.description,
                                style = SettingsBodySubStyle,
                                color = ColorTextMuted,
                            )
                        }
                    }
                }
                if (state.distancePreset == DistancePreset.CUSTOM) {
                    Spacer(Modifier.height(4.dp))
                    Text(
                        text  = "Custom distances configured on the DOPE screen.",
                        style = SettingsBodySubStyle,
                        color = ColorTextMuted,
                    )
                }
            }

            // ── Measurement system ────────────────────────────────────────────
            InstrumentPanel(label = "Measurement System") {
                MeasureSystem.entries.forEach { system ->
                    Row(
                        modifier          = Modifier
                            .fillMaxWidth()
                            .clickable { sessionVm.setMeasureSystem(system) }
                            .padding(vertical = 4.dp),
                        verticalAlignment = Alignment.CenterVertically,
                    ) {
                        RadioButton(
                            selected  = state.measureSystem == system,
                            onClick   = { sessionVm.setMeasureSystem(system) },
                            colors    = RadioButtonDefaults.colors(selectedColor = ColorAmber),
                        )
                        Spacer(Modifier.width(8.dp))
                        Column {
                            Text(
                                text  = when (system) {
                                    MeasureSystem.US_CUSTOMARY -> "US Customary"
                                    MeasureSystem.METRIC       -> "Metric"
                                },
                                style = SettingsBodyStyle,
                                color = ColorTextPrimary,
                            )
                            Text(
                                text  = when (system) {
                                    MeasureSystem.US_CUSTOMARY -> "ft, °F, inHg, mph"
                                    MeasureSystem.METRIC       -> "m, °C, hPa, km/h"
                                },
                                style = SettingsBodySubStyle,
                                color = ColorTextMuted,
                            )
                        }
                    }
                }
                Spacer(Modifier.height(2.dp))
                Text(
                    text  = "Override individual units in Advanced Settings → Measurement Units.",
                    style = SettingsBodySubStyle,
                    color = ColorTextMuted,
                )
            }

            // ── Label format ──────────────────────────────────────────────────
            val isCircle   = state.labelFormat.shape is LabelShape.Circle
            val isRect     = !isCircle
            val sizeGroup  = state.labelFormat.sizeGroup
            val isMultiCol = state.labelFormat.columns >= 2

            InstrumentPanel(label = "Label Format") {
                LabelSizeGroup.entries.forEach { group ->
                    val isSelected = sizeGroup == group
                    Row(
                        modifier          = Modifier
                            .fillMaxWidth()
                            .clickable {
                                if (!isSelected) sessionVm.setLabelFormat(LabelFormats.defaultForSizeGroup[group]!!)
                            }
                            .padding(vertical = 4.dp),
                        verticalAlignment = Alignment.CenterVertically,
                    ) {
                        RadioButton(
                            selected = isSelected,
                            onClick  = {
                                if (!isSelected) sessionVm.setLabelFormat(LabelFormats.defaultForSizeGroup[group]!!)
                            },
                            colors = RadioButtonDefaults.colors(selectedColor = ColorAmber),
                        )
                        Spacer(Modifier.width(8.dp))
                        Text(
                            text  = group.sizeName,
                            style = SettingsBodyStyle,
                            color = ColorTextPrimary,
                        )
                    }
                }

                // 38 mm / Full 50 mm — circle only
                if (isCircle) {
                    SectionDivider(Modifier.padding(vertical = 6.dp))
                    listOf(false, true).forEach { full ->
                        Row(
                            modifier          = Modifier
                                .fillMaxWidth()
                                .clickable { printerVm.setPrintFullCircle(full) }
                                .padding(vertical = 4.dp),
                            verticalAlignment = Alignment.CenterVertically,
                        ) {
                            RadioButton(
                                selected = printerUiState.printFullCircle == full,
                                onClick  = { printerVm.setPrintFullCircle(full) },
                                colors   = RadioButtonDefaults.colors(selectedColor = ColorAmber),
                            )
                            Spacer(Modifier.width(8.dp))
                            Column {
                                Text(
                                    text  = if (full) "Full 50 mm  (1.97\")" else "38 mm  (1.50\")",
                                    style = SettingsBodyStyle,
                                    color = ColorTextPrimary,
                                )
                                Text(
                                    text  = if (full) "Uses entire label" else "Leaves punch guide hairline",
                                    style = SettingsBodySubStyle,
                                    color = ColorTextMuted,
                                )
                            }
                        }
                    }
                }

                // Layout — rect labels only
                if (isRect) {
                    SectionDivider(Modifier.padding(vertical = 6.dp))
                    LabelFormats.allBySizeGroup[sizeGroup].orEmpty().forEach { fmt ->
                        Row(
                            modifier          = Modifier
                                .fillMaxWidth()
                                .clickable { sessionVm.setLabelFormat(fmt) }
                                .padding(vertical = 4.dp),
                            verticalAlignment = Alignment.CenterVertically,
                        ) {
                            RadioButton(
                                selected = state.labelFormat == fmt,
                                onClick  = { sessionVm.setLabelFormat(fmt) },
                                colors   = RadioButtonDefaults.colors(selectedColor = ColorAmber),
                            )
                            Spacer(Modifier.width(8.dp))
                            Column {
                                Text(
                                    text  = layoutTitle(fmt),
                                    style = SettingsBodyStyle,
                                    color = ColorTextPrimary,
                                )
                                Text(
                                    text  = layoutSubtitle(fmt),
                                    style = SettingsBodySubStyle,
                                    color = ColorTextMuted,
                                )
                            }
                        }
                    }
                }

                // Column 1 field order — multi-column rect only
                if (isRect && isMultiCol) {
                    SectionDivider(Modifier.padding(vertical = 6.dp))
                    Text(
                        text  = "Column 1 Field Order",
                        style = SettingsBodyStyle,
                        color = ColorTextPrimary,
                    )
                    listOf(true, false).forEach { reversed ->
                        Row(
                            modifier          = Modifier
                                .fillMaxWidth()
                                .clickable { printerVm.setLandscapeCol1Reversed(reversed) }
                                .padding(vertical = 4.dp),
                            verticalAlignment = Alignment.CenterVertically,
                        ) {
                            RadioButton(
                                selected = printerUiState.landscapeCol1Reversed == reversed,
                                onClick  = { printerVm.setLandscapeCol1Reversed(reversed) },
                                colors   = RadioButtonDefaults.colors(selectedColor = ColorAmber),
                            )
                            Spacer(Modifier.width(8.dp))
                            Column {
                                Text(
                                    text  = if (reversed) "Reversed (default)" else "Same as column 2",
                                    style = SettingsBodyStyle,
                                    color = ColorTextPrimary,
                                )
                                Text(
                                    text  = if (reversed) "Windage — Elevation — Distance"
                                            else "Distance — Elevation — Windage",
                                    style = SettingsBodySubStyle,
                                    color = ColorTextMuted,
                                )
                            }
                        }
                    }
                }
            }

            // ── Advanced Settings ─────────────────────────────────────────────
            InstrumentPanel(label = "Advanced") {
                Row(
                    modifier          = Modifier
                        .fillMaxWidth()
                        .clickable(onClick = onShowAdvanced)
                        .padding(vertical = 4.dp),
                    verticalAlignment = Alignment.CenterVertically,
                    horizontalArrangement = Arrangement.SpaceBetween,
                ) {
                    Column(Modifier.weight(1f)) {
                        Text(
                            text  = "Advanced Settings",
                            style = SettingsBodyStyle,
                            color = ColorAmber,
                        )
                        Text(
                            text  = "Ballistics engine · Corrections · Measurement units · Label appearance · Weather sensor",
                            style = SettingsBodySubStyle,
                            color = ColorTextMuted,
                        )
                    }
                    Icon(
                        imageVector        = Icons.AutoMirrored.Filled.ArrowForward,
                        contentDescription = null,
                        tint               = ColorAmberDim,
                    )
                }
            }

            // ── Privacy ───────────────────────────────────────────────────────
            InstrumentPanel(label = "Privacy") {
                Row(
                    modifier          = Modifier.fillMaxWidth(),
                    verticalAlignment = Alignment.CenterVertically,
                    horizontalArrangement = Arrangement.SpaceBetween,
                ) {
                    Column(Modifier.weight(1f)) {
                        Text(
                            text  = "Send crash reports",
                            style = SettingsBodyStyle,
                            color = ColorTextPrimary,
                        )
                        Text(
                            text  = if (crashReportingEnabled)
                                "Sending anonymous crash diagnostics to help fix bugs. No personal, location, or ballistic data is sent."
                            else
                                "Off. No crash data leaves your device. The app works exactly the same either way.",
                            style = SettingsBodySubStyle,
                            color = if (crashReportingEnabled) ColorAmber else ColorTextMuted,
                        )
                    }
                    Switch(
                        checked         = crashReportingEnabled,
                        onCheckedChange = { crashConsentVm.setEnabled(it) },
                        colors          = SwitchDefaults.colors(
                            checkedThumbColor = ColorBackground,
                            checkedTrackColor = ColorAmber,
                        ),
                    )
                }
            }

            // ── About ─────────────────────────────────────────────────────────
            fun sendEmail(address: String, subject: String = "") {
                val intent = Intent(Intent.ACTION_SENDTO, Uri.parse("mailto:$address")).apply {
                    if (subject.isNotEmpty()) putExtra(Intent.EXTRA_SUBJECT, subject)
                }
                context.startActivity(Intent.createChooser(intent, null))
            }

            InstrumentPanel(label = "About") {
                Text("ScopeDOPE", style = SettingsBodyStyle, color = ColorTextPrimary)
                // TEMP (DEBUG only): long-press version to throw a test crash for Sentry
                // pipeline verification. REMOVE before release — see SPEC §16.1 verification.
                Text(
                    "Version ${BuildConfig.VERSION_NAME}",
                    style = SettingsBodySubStyle,
                    color = ColorTextMuted,
                    modifier = if (BuildConfig.DEBUG) {
                        Modifier.pointerInput(Unit) {
                            detectTapGestures(
                                onLongPress = { throw RuntimeException("Sentry test crash (debug long-press)") }
                            )
                        }
                    } else Modifier,
                )
                Spacer(Modifier.height(2.dp))
                Text(
                    text  = "Developer: ScopeDOPE Development Team",
                    style = SettingsBodySubStyle,
                    color = ColorTextMuted,
                )
                SectionDivider(Modifier.padding(vertical = 8.dp))
                Text(
                    text  = "Precision ballistics engine with G1/G7 drag models and bias-corrected DOPE interpolation.",
                    style = MaterialTheme.typography.bodyMedium,
                    color = ColorTextMuted,
                )
                SectionDivider(Modifier.padding(vertical = 8.dp))
                Text(
                    text  = "DOPE file directory:",
                    style = SettingsBodySubStyle,
                    color = ColorTextMuted,
                )
                Text(
                    text  = sessionVm.dopeDirectoryPath,
                    style = MaterialTheme.typography.labelSmall,
                    color = ColorAmberDim,
                )
                SectionDivider(Modifier.padding(vertical = 8.dp))
                TextButton(
                    onClick  = onShowTutorial,
                    modifier = Modifier.fillMaxWidth(),
                ) {
                    Text("Watch Tutorial", style = SettingsBodySubStyle, color = ColorAmber)
                }
                TextButton(
                    onClick  = onShowFeedback,
                    modifier = Modifier.fillMaxWidth(),
                ) {
                    Text("Send Feedback", style = SettingsBodySubStyle, color = ColorAmber)
                }
                TextButton(
                    onClick  = onShowSupport,
                    modifier = Modifier.fillMaxWidth(),
                ) {
                    Text("Contact Support", style = SettingsBodySubStyle, color = ColorAmber)
                }
                TextButton(
                    onClick  = { sendEmail("info@scope-dope.com") },
                    modifier = Modifier.fillMaxWidth(),
                ) {
                    Text("General Info", style = SettingsBodySubStyle, color = ColorAmberDim)
                }
                TextButton(
                    onClick  = onResetOnboarding,
                    modifier = Modifier.fillMaxWidth(),
                ) {
                    Text(
                        text  = "Reset Onboarding Walkthrough",
                        style = SettingsBodySubStyle,
                        color = ColorAmberDim,
                    )
                }
            }
        }
    }
}
