package com.optix.android.ui.components

import androidx.compose.animation.core.*
import androidx.compose.foundation.Canvas
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.MaterialTheme
import androidx.compose.material3.Text
import androidx.compose.runtime.*
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.geometry.Offset
import androidx.compose.ui.graphics.*
import androidx.compose.ui.graphics.drawscope.DrawScope
import androidx.compose.ui.graphics.drawscope.Stroke
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
import com.optix.android.ui.theme.*
import kotlin.math.*

// ── HUD panel card (corner bracket style) ────────────────────────────────────
@Composable
fun GlassCard(
    modifier: Modifier = Modifier,
    accentColor: Color = NeonRed,
    cornerRadius: Dp = 4.dp,
    content: @Composable BoxScope.() -> Unit,
) {
    Box(
        modifier = modifier
            .clip(RoundedCornerShape(cornerRadius))
            .background(T.surfaceGradient)
            .drawBehind {
                val stroke = 1.dp.toPx()
                val bracket = 18.dp.toPx()
                val w = size.width
                val h = size.height
                val c = accentColor

                // Full dim border
                drawRect(c.copy(alpha = 0.15f), style = Stroke(stroke))

                // Corner bracket accents
                drawLine(c, Offset(0f, bracket), Offset(0f, 0f), stroke * 2)
                drawLine(c, Offset(0f, 0f), Offset(bracket, 0f), stroke * 2)
                drawLine(c, Offset(w - bracket, 0f), Offset(w, 0f), stroke * 2)
                drawLine(c, Offset(w, 0f), Offset(w, bracket), stroke * 2)
                drawLine(c, Offset(0f, h - bracket), Offset(0f, h), stroke * 2)
                drawLine(c, Offset(0f, h), Offset(bracket, h), stroke * 2)
                drawLine(c, Offset(w - bracket, h), Offset(w, h), stroke * 2)
                drawLine(c, Offset(w, h - bracket), Offset(w, h), stroke * 2)
            }
            .padding(16.dp),
        content = content,
    )
}

// ── HUD button ────────────────────────────────────────────────────────────────
@Composable
fun NeonButton(
    label: String,
    onClick: () -> Unit,
    modifier: Modifier = Modifier,
    color: Color = NeonRed,
    enabled: Boolean = true,
) {
    val tSurfaceVar = T.surfaceVar
    val tBorder = T.border
    Box(
        modifier = modifier
            .clip(RoundedCornerShape(3.dp))
            .background(if (enabled) color else tSurfaceVar)
            .drawBehind {
                if (!enabled) drawRect(tBorder, style = Stroke(1f))
            }
            .clickable(enabled = enabled, onClick = onClick)
            .padding(horizontal = 20.dp, vertical = 12.dp),
        contentAlignment = Alignment.Center,
    ) {
        Text(
            label,
            color = if (enabled) (if (T.isDark) Color.Black else Color.White) else T.onSurfaceMid,
            style = MaterialTheme.typography.labelLarge,
        )
    }
}

// ── Pulsing radar ring ────────────────────────────────────────────────────────
@Composable
fun RadarPulse(
    modifier: Modifier = Modifier,
    color: Color = NeonRedGlow,
    rings: Int = 3,
) {
    val infiniteTransition = rememberInfiniteTransition(label = "radar")
    val sweep by infiniteTransition.animateFloat(
        initialValue = 0f, targetValue = 360f,
        animationSpec = infiniteRepeatable(tween(2400, easing = LinearEasing)),
        label = "sweep",
    )
    val pulseScale by infiniteTransition.animateFloat(
        initialValue = 0f, targetValue = 1f,
        animationSpec = infiniteRepeatable(tween(1800, easing = FastOutSlowInEasing)),
        label = "pulse",
    )

    Canvas(modifier = modifier) {
        val cx = size.width / 2f
        val cy = size.height / 2f
        val maxR = minOf(cx, cy)

        for (i in 1..rings) {
            val r = maxR * i / rings
            drawCircle(
                color = color.copy(alpha = 0.15f),
                radius = r,
                center = Offset(cx, cy),
                style = Stroke(width = 1.dp.toPx()),
            )
        }

        drawArc(
            brush = Brush.sweepGradient(
                0f to Color.Transparent,
                0.7f to color.copy(alpha = 0.0f),
                1f to color.copy(alpha = 0.4f),
                center = Offset(cx, cy),
            ),
            startAngle = sweep - 90f,
            sweepAngle = 120f,
            useCenter = true,
        )

        drawCircle(
            color = color.copy(alpha = (1f - pulseScale) * 0.4f),
            radius = maxR * pulseScale,
            center = Offset(cx, cy),
            style = Stroke(width = 2.dp.toPx()),
        )

        drawCircle(color = color, radius = 5.dp.toPx(), center = Offset(cx, cy))
    }
}

// ── Hex grid background decoration ───────────────────────────────────────────
@Composable
fun HexGrid(
    modifier: Modifier = Modifier,
    color: Color = NeonRed.copy(alpha = 0.08f),
    cellSize: Float = 40f,
) {
    Canvas(modifier = modifier) {
        val cols = (size.width / (cellSize * 1.5f)).toInt() + 2
        val rows = (size.height / (cellSize * sqrt(3f))).toInt() + 2
        for (col in 0..cols) {
            for (row in 0..rows) {
                val x = col * cellSize * 1.5f
                val y = row * cellSize * sqrt(3f) + if (col % 2 == 1) cellSize * sqrt(3f) / 2 else 0f
                drawHexagon(Offset(x, y), cellSize * 0.9f, color)
            }
        }
    }
}

private fun DrawScope.drawHexagon(center: Offset, size: Float, color: Color) {
    val path = Path()
    for (i in 0..5) {
        val angle = Math.toRadians((60.0 * i) - 30.0)
        val x = center.x + size * cos(angle).toFloat()
        val y = center.y + size * sin(angle).toFloat()
        if (i == 0) path.moveTo(x, y) else path.lineTo(x, y)
    }
    path.close()
    drawPath(path, color, style = Stroke(width = 1f))
}

// ── Animated scan progress bar ────────────────────────────────────────────────
@Composable
fun NeonProgressBar(
    progress: Pair<Int, Int>?,
    modifier: Modifier = Modifier,
    color: Color = NeonRed,
) {
    if (progress == null) return
    val (current, total) = progress
    val fraction = if (total > 0) current.toFloat() / total else 0f
    val animFraction by animateFloatAsState(fraction, tween(300), label = "prog")

    Column(modifier = modifier) {
        Row(
            Modifier.fillMaxWidth(),
            horizontalArrangement = Arrangement.SpaceBetween,
        ) {
            Text("PROGRESS", color = color, style = MaterialTheme.typography.labelSmall)
            Text("$current / $total", color = T.onSurfaceMid, style = MaterialTheme.typography.labelSmall)
        }
        Spacer(Modifier.height(4.dp))
        Box(
            Modifier
                .fillMaxWidth()
                .height(4.dp)
                .background(T.border.copy(alpha = 0.3f), RoundedCornerShape(2.dp))
        ) {
            Box(
                Modifier
                    .fillMaxWidth(animFraction)
                    .fillMaxHeight()
                    .background(
                        Brush.horizontalGradient(listOf(color.copy(alpha = 0.6f), color)),
                        RoundedCornerShape(2.dp),
                    )
            )
        }
    }
}

// ── Neon text field colors helper ─────────────────────────────────────────────
@Composable
fun neonTextFieldColors(accent: Color = NeonRed) = androidx.compose.material3.OutlinedTextFieldDefaults.colors(
    focusedBorderColor      = accent,
    unfocusedBorderColor    = T.border,
    focusedLabelColor       = accent,
    cursorColor             = accent,
    focusedTextColor        = T.onSurface,
    unfocusedTextColor      = T.onSurface,
    focusedContainerColor   = T.surfaceVar.copy(alpha = 0.5f),
    unfocusedContainerColor = T.surfaceVar.copy(alpha = 0.3f),
)

// ── Stat chip (small labeled value) ──────────────────────────────────────────
@Composable
fun StatChip(label: String, value: String, color: Color = NeonRed) {
    Column(
        modifier = Modifier
            .background(color.copy(alpha = 0.08f), RoundedCornerShape(8.dp))
            .border(1.dp, color.copy(alpha = 0.3f), RoundedCornerShape(8.dp))
            .padding(horizontal = 12.dp, vertical = 8.dp),
        horizontalAlignment = Alignment.CenterHorizontally,
    ) {
        Text(value, color = color, style = MaterialTheme.typography.titleMedium)
        Text(label, color = T.onSurfaceMid, style = MaterialTheme.typography.labelSmall)
    }
}
