package club.clubk.ktag.apps.sentry

import android.Manifest
import android.content.pm.PackageManager
import android.os.Bundle
import android.util.Log
import androidx.activity.ComponentActivity
import androidx.activity.compose.setContent
import androidx.activity.result.contract.ActivityResultContracts
import androidx.camera.core.CameraSelector
import androidx.camera.core.ImageAnalysis
import androidx.camera.core.Preview
import androidx.camera.lifecycle.ProcessCameraProvider
import androidx.camera.view.PreviewView
import androidx.compose.foundation.Canvas
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Settings
import androidx.compose.material3.Button
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.DropdownMenu
import androidx.compose.material3.DropdownMenuItem
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedButton
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBar
import androidx.compose.material3.TopAppBarDefaults
import androidx.compose.runtime.Composable
import androidx.compose.runtime.DisposableEffect
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableLongStateOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import kotlinx.coroutines.delay
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.geometry.Offset
import androidx.compose.ui.geometry.Size
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.drawscope.Stroke
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.platform.LocalLifecycleOwner
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.compose.ui.viewinterop.AndroidView
import androidx.core.content.ContextCompat
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.LifecycleEventObserver
import androidx.lifecycle.viewmodel.compose.viewModel
import club.clubk.ktag.apps.core.UsbSerialManager
import com.hoho.android.usbserial.driver.UsbSerialDriver
import java.util.concurrent.Executors

private const val TAG = "SentryActivity"

class SentryActivity : ComponentActivity() {

    private val requestCameraPermission = registerForActivityResult(
        ActivityResultContracts.RequestPermission()
    ) { granted ->
        if (!granted) {
            Log.w(TAG, "Camera permission denied")
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        if (ContextCompat.checkSelfPermission(this, Manifest.permission.CAMERA)
            != PackageManager.PERMISSION_GRANTED
        ) {
            requestCameraPermission.launch(Manifest.permission.CAMERA)
        }
        setContent {
            MaterialTheme {
                Surface(modifier = Modifier.fillMaxSize()) {
                    SentryScreen()
                }
            }
        }
    }
}

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun SentryScreen(vm: SentryViewModel = viewModel()) {
    val context = LocalContext.current
    val lifecycleOwner = LocalLifecycleOwner.current

    val connectionState by vm.connectionState.collectAsState()
    val availableDevices by vm.availableDevices.collectAsState()
    val detectionResult by vm.detectionResult.collectAsState()
    val lastTriggerMs by vm.lastTriggerMs.collectAsState()
    val config by vm.config.collectAsState()

    var selectedDevice by remember { mutableStateOf<UsbSerialDriver?>(null) }
    var showDeviceMenu by remember { mutableStateOf(false) }
    val cameraExecutor = remember { Executors.newSingleThreadExecutor() }

    // Register/unregister USB
    DisposableEffect(vm) {
        vm.registerUsb()
        onDispose { vm.unregisterUsb() }
    }

    // Cleanup camera executor on disposal
    DisposableEffect(cameraExecutor) {
        onDispose { cameraExecutor.shutdown() }
    }

    // Reload config on every resume so settings changes take effect immediately
    DisposableEffect(lifecycleOwner) {
        val observer = LifecycleEventObserver { _, event ->
            if (event == Lifecycle.Event.ON_RESUME) vm.reloadConfig()
        }
        lifecycleOwner.lifecycle.addObserver(observer)
        onDispose { lifecycleOwner.lifecycle.removeObserver(observer) }
    }

    // Auto-select first available device
    LaunchedEffect(availableDevices) {
        if (selectedDevice == null && availableDevices.isNotEmpty()) {
            selectedDevice = availableDevices.first()
        }
        if (selectedDevice != null && availableDevices.none {
                it.device.deviceId == selectedDevice?.device?.deviceId
            }
        ) {
            selectedDevice = null
        }
    }

    val teamLabel = when (config.team) {
        "asblue" -> "Blue"
        "asred" -> "Red"
        "aspurple" -> "Purple"
        else -> config.team
    }

    var currentTimeMs by remember { mutableLongStateOf(System.currentTimeMillis()) }
    LaunchedEffect(Unit) {
        while (true) {
            delay(500)
            currentTimeMs = System.currentTimeMillis()
        }
    }

    val secondsSinceTrigger = if (lastTriggerMs > 0L) {
        (currentTimeMs - lastTriggerMs) / 1000
    } else null

    Scaffold(
        topBar = {
            TopAppBar(
                title = { Text("Sentry") },
                colors = TopAppBarDefaults.topAppBarColors(
                    containerColor = Color(0xFF323031),
                    titleContentColor = Color(0xFFFFC857),
                    actionIconContentColor = Color(0xFFFFC857)
                ),
                actions = {
                    IconButton(onClick = {
                        context.startActivity(SentrySettingsActivity.createIntent(context))
                    }) {
                        Icon(Icons.Default.Settings, contentDescription = "Settings")
                    }
                }
            )
        }
    ) { paddingValues ->
        Column(
            modifier = Modifier
                .fillMaxSize()
                .padding(paddingValues)
        ) {
            // Camera preview + bounding box overlay
            Box(
                modifier = Modifier
                    .weight(1f)
                    .fillMaxWidth()
            ) {
                // CameraX PreviewView - binds both Preview and ImageAnalysis
                val hasCameraPermission = ContextCompat.checkSelfPermission(
                    context, Manifest.permission.CAMERA
                ) == PackageManager.PERMISSION_GRANTED

                if (hasCameraPermission) {
                    AndroidView(
                        factory = { ctx ->
                            val previewView = PreviewView(ctx).apply {
                                scaleType = PreviewView.ScaleType.FILL_CENTER
                            }

                            val cameraProviderFuture = ProcessCameraProvider.getInstance(ctx)
                            cameraProviderFuture.addListener({
                                val cameraProvider = cameraProviderFuture.get()

                                val preview = Preview.Builder().build().also {
                                    it.surfaceProvider = previewView.surfaceProvider
                                }

                                val imageAnalysis = ImageAnalysis.Builder()
                                    .setBackpressureStrategy(ImageAnalysis.STRATEGY_KEEP_ONLY_LATEST)
                                    .build()
                                    .also { analysis ->
                                        analysis.setAnalyzer(cameraExecutor, vm.buildAnalyzer())
                                    }

                                try {
                                    cameraProvider.unbindAll()
                                    cameraProvider.bindToLifecycle(
                                        lifecycleOwner,
                                        CameraSelector.DEFAULT_BACK_CAMERA,
                                        preview,
                                        imageAnalysis
                                    )
                                } catch (e: Exception) {
                                    Log.e(TAG, "Camera binding failed", e)
                                }
                            }, ContextCompat.getMainExecutor(ctx))

                            previewView
                        },
                        modifier = Modifier.fillMaxSize()
                    )
                } else {
                    Box(
                        modifier = Modifier
                            .fillMaxSize()
                            .background(Color.Black),
                        contentAlignment = Alignment.Center
                    ) {
                        Text("Camera permission required", color = Color.White)
                    }
                }

                // Bounding box + crosshair overlay
                Canvas(modifier = Modifier.fillMaxSize()) {
                    detectionResult?.let { result ->
                        val left = result.left * size.width
                        val top = result.top * size.height
                        val right = result.right * size.width
                        val bottom = result.bottom * size.height
                        drawRect(
                            color = Color.Red,
                            topLeft = Offset(left, top),
                            size = Size(right - left, bottom - top),
                            style = Stroke(width = 4f)
                        )
                    }

                    // Crosshair
                    val cx = size.width / 2f
                    val cy = size.height / 2f
                    val arm = minOf(size.width, size.height) * 0.08f
                    val gap = minOf(size.width, size.height) * 0.02f
                    val crosshairColor = Color.White
                    val strokeWidth = 3f
                    drawLine(crosshairColor, Offset(cx - arm - gap, cy), Offset(cx - gap, cy), strokeWidth)
                    drawLine(crosshairColor, Offset(cx + gap, cy), Offset(cx + arm + gap, cy), strokeWidth)
                    drawLine(crosshairColor, Offset(cx, cy - arm - gap), Offset(cx, cy - gap), strokeWidth)
                    drawLine(crosshairColor, Offset(cx, cy + gap), Offset(cx, cy + arm + gap), strokeWidth)
                }

                // Detected badge
                if (detectionResult != null) {
                    Box(
                        modifier = Modifier
                            .align(Alignment.TopEnd)
                            .padding(8.dp)
                            .background(Color.Red, shape = MaterialTheme.shapes.small)
                            .padding(horizontal = 8.dp, vertical = 4.dp)
                    ) {
                        Text("DETECTED", color = Color.White, fontSize = 12.sp)
                    }
                }
            }

            // Bottom control panel
            Column(
                modifier = Modifier
                    .fillMaxWidth()
                    .background(Color(0xFF323031))
                    .padding(8.dp)
            ) {
                // Device selector + connect button
                Row(
                    modifier = Modifier.fillMaxWidth(),
                    verticalAlignment = Alignment.CenterVertically
                ) {
                    Box(modifier = Modifier.weight(1f)) {
                        OutlinedButton(
                            onClick = { showDeviceMenu = true },
                            modifier = Modifier.fillMaxWidth()
                        ) {
                            Text(
                                text = selectedDevice?.device?.deviceName
                                    ?: if (availableDevices.isEmpty()) "No devices" else "Select device",
                                maxLines = 1,
                                color = Color.White
                            )
                        }
                        DropdownMenu(
                            expanded = showDeviceMenu,
                            onDismissRequest = { showDeviceMenu = false }
                        ) {
                            if (availableDevices.isEmpty()) {
                                DropdownMenuItem(
                                    text = { Text("No USB serial devices found") },
                                    onClick = { showDeviceMenu = false }
                                )
                            } else {
                                availableDevices.forEach { driver ->
                                    DropdownMenuItem(
                                        text = {
                                            Text(
                                                "${driver.device.deviceName} " +
                                                    "(${driver.javaClass.simpleName.removeSuffix("Driver")})"
                                            )
                                        },
                                        onClick = {
                                            selectedDevice = driver
                                            showDeviceMenu = false
                                        }
                                    )
                                }
                            }
                        }
                    }

                    Spacer(modifier = Modifier.width(8.dp))

                    Button(
                        onClick = {
                            when (connectionState) {
                                UsbSerialManager.ConnectionState.CONNECTED -> vm.disconnect()
                                UsbSerialManager.ConnectionState.DISCONNECTED,
                                UsbSerialManager.ConnectionState.ERROR -> {
                                    selectedDevice?.let { vm.connect(it) }
                                }
                                else -> {}
                            }
                        },
                        enabled = selectedDevice != null &&
                            connectionState != UsbSerialManager.ConnectionState.CONNECTING &&
                            connectionState != UsbSerialManager.ConnectionState.AWAITING_PERMISSION,
                        colors = ButtonDefaults.buttonColors(
                            containerColor = if (connectionState == UsbSerialManager.ConnectionState.CONNECTED)
                                MaterialTheme.colorScheme.error
                            else
                                MaterialTheme.colorScheme.primary
                        )
                    ) {
                        Text(
                            when (connectionState) {
                                UsbSerialManager.ConnectionState.CONNECTED -> "Disconnect"
                                UsbSerialManager.ConnectionState.CONNECTING -> "Connecting..."
                                UsbSerialManager.ConnectionState.AWAITING_PERMISSION -> "Requesting..."
                                else -> "Connect"
                            }
                        )
                    }
                }

                // Status row
                Row(
                    modifier = Modifier
                        .fillMaxWidth()
                        .padding(top = 4.dp),
                    verticalAlignment = Alignment.CenterVertically
                ) {
                    val stateColor = when (connectionState) {
                        UsbSerialManager.ConnectionState.CONNECTED -> Color(0xFF4BA838)
                        UsbSerialManager.ConnectionState.ERROR -> Color.Red
                        else -> Color.Gray
                    }
                    Text(
                        text = connectionState.name,
                        color = stateColor,
                        fontSize = 12.sp
                    )
                    Text(
                        text = "  |  Team: $teamLabel",
                        color = Color.White,
                        fontSize = 12.sp
                    )
                    if (secondsSinceTrigger != null) {
                        Text(
                            text = "  |  Last trigger: ${secondsSinceTrigger}s ago",
                            color = Color(0xFFFFC857),
                            fontSize = 12.sp
                        )
                    }
                }
            }
        }
    }
}
