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

import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.text.KeyboardActions
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.material3.*
import androidx.compose.runtime.Composable
import androidx.compose.runtime.remember
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.draw.drawBehind
import androidx.compose.ui.focus.FocusDirection
import androidx.compose.ui.focus.FocusRequester
import androidx.compose.ui.focus.focusRequester
import androidx.compose.ui.focus.onFocusChanged
import androidx.compose.ui.platform.LocalFocusManager
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.geometry.Size
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.Outline
import androidx.compose.ui.graphics.Path
import androidx.compose.ui.graphics.Shape
import androidx.compose.ui.graphics.drawscope.Stroke
import androidx.compose.ui.text.input.ImeAction
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.unit.Density
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.LayoutDirection
import androidx.compose.ui.unit.dp
import com.coldboreballisticsllc.scopedope.ui.theme.*

// ── Notched corner shape (clip-path polygon equivalent) ───────────────────────

class NotchedCornerShape(private val notchDp: Dp) : Shape {
    override fun createOutline(size: Size, layoutDirection: LayoutDirection, density: Density) =
        Outline.Generic(Path().apply {
            val n = with(density) { notchDp.toPx() }
            moveTo(n, 0f)
            lineTo(size.width - n, 0f)
            lineTo(size.width, n)
            lineTo(size.width, size.height - n)
            lineTo(size.width - n, size.height)
            lineTo(n, size.height)
            lineTo(0f, size.height - n)
            lineTo(0f, n)
            close()
        })
}

// ── Instrument panel with floating label + TL/BR corner brackets ──────────────

@Composable
fun InstrumentPanel(
    label:    String,
    modifier: Modifier = Modifier,
    content:  @Composable ColumnScope.() -> Unit,
) {
    Box(modifier = modifier) {
        Column(
            modifier = Modifier
                .padding(top = 9.dp)
                .fillMaxWidth()
                .background(ColorSurface)
                .drawBehind {
                    val borderStroke = 1.dp.toPx()
                    val bracketLen   = 12.dp.toPx()
                    val bracketStroke = 2.dp.toPx()
                    drawRect(color = ColorBorder, style = Stroke(width = borderStroke))
                    // TL bracket
                    drawLine(ColorAmberDim, Offset(0f, bracketLen), Offset(0f, 0f), bracketStroke)
                    drawLine(ColorAmberDim, Offset(0f, 0f), Offset(bracketLen, 0f), bracketStroke)
                    // BR bracket
                    drawLine(ColorAmberDim, Offset(size.width, size.height - bracketLen), Offset(size.width, size.height), bracketStroke)
                    drawLine(ColorAmberDim, Offset(size.width, size.height), Offset(size.width - bracketLen, size.height), bracketStroke)
                }
                .padding(start = 14.dp, end = 14.dp, top = 14.dp, bottom = 14.dp),
        ) {
            content()
        }

        // Floating label that overlays the top border
        Row(
            modifier = Modifier
                .align(Alignment.TopStart)
                .padding(start = 14.dp)
                .background(ColorSurface)
                .padding(horizontal = 6.dp),
            verticalAlignment     = Alignment.CenterVertically,
            horizontalArrangement = Arrangement.spacedBy(5.dp),
        ) {
            Box(Modifier.width(6.dp).height(1.dp).background(ColorAmberDim.copy(alpha = 0.55f)))
            Text(
                text  = label.uppercase(),
                style = PanelLabelStyle,
                color = ColorAmberDim,
            )
            Box(Modifier.width(6.dp).height(1.dp).background(ColorAmberDim.copy(alpha = 0.55f)))
        }
    }
}

// ── Action button with notched corners ───────────────────────────────────────

@Composable
fun ActionButton(
    text:     String,
    onClick:  () -> Unit,
    modifier: Modifier = Modifier,
    enabled:  Boolean  = true,
    height:   Dp       = 68.dp,
    notch:    Dp       = 8.dp,
) {
    val shape = remember(notch) { NotchedCornerShape(notch) }
    Box(
        modifier = modifier
            .height(height)
            .clip(shape)
            .background(if (enabled) ColorAmber else ColorSurface2)
            .clickable(enabled = enabled, onClick = onClick),
        contentAlignment = Alignment.Center,
    ) {
        Text(
            text  = text,
            style = ActionButtonStyle,
            color = if (enabled) Color.Black else ColorTextMuted,
        )
    }
}

// ── Numeric input field with 20sp bold mono text + 12sp field label ───────────

@Composable
fun NumericField(
    value:          String,
    onValueChange:  (String) -> Unit,
    label:          String,
    modifier:       Modifier        = Modifier,
    suffix:         String          = "",
    imeAction:      ImeAction       = ImeAction.Next,
    focusRequester: FocusRequester? = null,
    onDone:         () -> Unit      = {},
    onNext:         (() -> Unit)?   = null,
    onFocusLost:    () -> Unit      = {},
) {
    // Default Next behavior: advance focus to the next field in layout order.
    // Callers may override onNext (e.g. to focus a specific field).
    val focusManager = LocalFocusManager.current
    val handleNext: () -> Unit = onNext ?: { focusManager.moveFocus(FocusDirection.Next) }
    Column(modifier = modifier) {
        Text(
            text  = label.uppercase(),
            style = FieldLabelStyle,
            color = ColorTextMuted,
        )
        Spacer(Modifier.height(4.dp))
        OutlinedTextField(
            value            = value,
            onValueChange    = onValueChange,
            suffix           = if (suffix.isNotEmpty()) {{ Text(suffix, style = FieldLabelStyle, color = ColorTextMuted) }} else null,
            singleLine       = true,
            keyboardOptions  = KeyboardOptions(
                keyboardType = KeyboardType.Decimal,
                imeAction    = imeAction,
            ),
            keyboardActions  = KeyboardActions(onDone = { onDone() }, onNext = { handleNext() }),
            colors           = OutlinedTextFieldDefaults.colors(
                focusedBorderColor      = ColorAmber,
                unfocusedBorderColor    = ColorBorder,
                focusedLabelColor       = ColorAmber,
                cursorColor             = ColorAmber,
                focusedContainerColor   = ColorBackground,
                unfocusedContainerColor = ColorBackground,
                focusedTextColor        = ColorTextPrimary,
                unfocusedTextColor      = ColorTextPrimary,
            ),
            textStyle        = DataValueStyle.copy(color = ColorTextPrimary),
            modifier         = Modifier
                .fillMaxWidth()
                .heightIn(min = 56.dp)
                .then(if (focusRequester != null) Modifier.focusRequester(focusRequester) else Modifier)
                .onFocusChanged { if (!it.isFocused) onFocusLost() },
        )
    }
}

// ── Text input field (names/labels) ──────────────────────────────────────────

@Composable
fun LabelTextField(
    value:         String,
    onValueChange: (String) -> Unit,
    label:         String,
    modifier:      Modifier  = Modifier,
    imeAction:     ImeAction = ImeAction.Next,
    onFocusLost:   () -> Unit = {},
) {
    val focusManager = LocalFocusManager.current
    Column(modifier = modifier) {
        Text(
            text  = label.uppercase(),
            style = FieldLabelStyle,
            color = ColorTextMuted,
        )
        Spacer(Modifier.height(4.dp))
        OutlinedTextField(
            value            = value,
            onValueChange    = onValueChange,
            singleLine       = true,
            keyboardOptions  = KeyboardOptions(
                keyboardType = KeyboardType.Text,
                imeAction    = imeAction,
            ),
            keyboardActions  = KeyboardActions(
                onDone = { onFocusLost() },
                onNext = { focusManager.moveFocus(FocusDirection.Next) },
            ),
            colors           = OutlinedTextFieldDefaults.colors(
                focusedBorderColor      = ColorAmber,
                unfocusedBorderColor    = ColorBorder,
                focusedLabelColor       = ColorAmber,
                cursorColor             = ColorAmber,
                focusedContainerColor   = ColorBackground,
                unfocusedContainerColor = ColorBackground,
                focusedTextColor        = ColorTextPrimary,
                unfocusedTextColor      = ColorTextPrimary,
            ),
            textStyle        = DataValueStyle.copy(color = ColorTextPrimary),
            modifier         = Modifier
                .fillMaxWidth()
                .heightIn(min = 56.dp)
                .onFocusChanged { if (!it.isFocused) onFocusLost() },
        )
    }
}

// ── Labeled key/value row ─────────────────────────────────────────────────────

@Composable
fun LabeledValue(
    label:    String,
    value:    String,
    color:    Color    = ColorTextPrimary,
    modifier: Modifier = Modifier,
) {
    Row(
        modifier              = modifier.fillMaxWidth(),
        horizontalArrangement = Arrangement.SpaceBetween,
        verticalAlignment     = Alignment.CenterVertically,
    ) {
        Text(label, style = BodySubStyle, color = ColorTextMuted)
        Text(value, style = BodySubStyle.copy(fontFamily = PlexMono), color = color)
    }
}

// ── Horizontal divider ────────────────────────────────────────────────────────

@Composable
fun SectionDivider(modifier: Modifier = Modifier) {
    HorizontalDivider(modifier = modifier, color = ColorBorder)
}
