package com.lazy.emulate.ui.screens.controller

import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.BoxWithConstraints
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.height
import androidx.compose.foundation.layout.heightIn
import androidx.compose.foundation.layout.offset
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.verticalScroll
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.ArrowBack
import androidx.compose.material.icons.filled.Delete
import androidx.compose.material.icons.filled.Refresh
import androidx.compose.material3.Card
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.HorizontalDivider
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBar
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.IntOffset
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.lazy.emulate.input.ControllerManager
import com.lazy.emulate.input.GamepadButton
import com.lazy.emulate.input.UsbDeviceInfo

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun ControllerTestScreen(
    controllerManager: ControllerManager,
    onBack: () -> Unit
) {
    val controllers by controllerManager.connectedControllers.collectAsState()
    val pressed by controllerManager.pressedButtons.collectAsState()
    val analog by controllerManager.analogSnapshot.collectAsState()
    val log by controllerManager.rawEventLog.collectAsState()
    val usbDevices by controllerManager.usbDevices.collectAsState()

    LaunchedEffect(Unit) { controllerManager.refreshUsbDevices() }

    Scaffold(
        topBar = {
            TopAppBar(
                title = { Text("Test Controller") },
                navigationIcon = {
                    IconButton(onClick = onBack) {
                        Icon(Icons.AutoMirrored.Filled.ArrowBack, contentDescription = "Back")
                    }
                },
                actions = {
                    IconButton(onClick = { controllerManager.clearEventLog() }) {
                        Icon(Icons.Default.Delete, contentDescription = "Clear log")
                    }
                }
            )
        }
    ) { padding ->
        Column(
            modifier = Modifier
                .fillMaxSize()
                .padding(padding)
                .verticalScroll(rememberScrollState())
                .padding(horizontal = 16.dp, vertical = 12.dp)
        ) {
            // Detected devices
            Text(
                "Detected Controllers (${controllers.size})",
                style = MaterialTheme.typography.titleMedium
            )
            Spacer(Modifier.height(6.dp))
            Card(modifier = Modifier.fillMaxWidth()) {
                if (controllers.isEmpty()) {
                    Text(
                        "None — press a button or re-pair the controller.",
                        modifier = Modifier.padding(12.dp),
                        style = MaterialTheme.typography.bodyMedium,
                        color = MaterialTheme.colorScheme.onSurfaceVariant
                    )
                } else {
                    controllers.forEachIndexed { i, c ->
                        Column(modifier = Modifier.padding(12.dp)) {
                            Text(c.name, fontWeight = FontWeight.SemiBold)
                            Text(
                                "vendor=0x${"%04x".format(c.vendorId)}  product=0x${"%04x".format(c.productId)}  id=${c.deviceId}  ${if (c.isExternal) "external" else "internal"}",
                                style = MaterialTheme.typography.bodySmall,
                                color = MaterialTheme.colorScheme.onSurfaceVariant
                            )
                        }
                        if (i < controllers.lastIndex) HorizontalDivider()
                    }
                }
            }

            Spacer(Modifier.height(16.dp))

            // USB devices — helps diagnose whether a USB host-mode adapter is enumerating.
            Row(
                modifier = Modifier.fillMaxWidth(),
                verticalAlignment = Alignment.CenterVertically,
                horizontalArrangement = Arrangement.SpaceBetween
            ) {
                Text(
                    "USB Devices (${usbDevices.size})",
                    style = MaterialTheme.typography.titleMedium
                )
                IconButton(onClick = { controllerManager.refreshUsbDevices() }) {
                    Icon(Icons.Default.Refresh, contentDescription = "Rescan USB")
                }
            }
            Spacer(Modifier.height(6.dp))
            Card(modifier = Modifier.fillMaxWidth()) {
                if (usbDevices.isEmpty()) {
                    Text(
                        "No USB host devices visible to the app. If you have an OTG adapter plugged in, tap rescan.",
                        modifier = Modifier.padding(12.dp),
                        style = MaterialTheme.typography.bodySmall,
                        color = MaterialTheme.colorScheme.onSurfaceVariant
                    )
                } else {
                    Column(modifier = Modifier.padding(12.dp)) {
                        usbDevices.forEachIndexed { i, d ->
                            UsbDeviceRow(d)
                            if (i < usbDevices.lastIndex) Spacer(Modifier.height(8.dp))
                        }
                    }
                }
            }

            Spacer(Modifier.height(16.dp))

            // Live button indicators
            Text("Pressed Buttons", style = MaterialTheme.typography.titleMedium)
            Spacer(Modifier.height(6.dp))
            ControllerDiagram(pressed = pressed)

            Spacer(Modifier.height(16.dp))

            // Analog readout
            Text("Axes", style = MaterialTheme.typography.titleMedium)
            Spacer(Modifier.height(6.dp))
            Card(modifier = Modifier.fillMaxWidth()) {
                Column(modifier = Modifier.padding(12.dp)) {
                    AxisRow("Left stick",  analog.lx, analog.ly)
                    AxisRow("Right stick", analog.rx, analog.ry)
                    AxisRow("D-pad (hat)", analog.hatX, analog.hatY)
                }
            }

            Spacer(Modifier.height(16.dp))

            // Raw event log
            Row(
                modifier = Modifier.fillMaxWidth(),
                verticalAlignment = Alignment.CenterVertically,
                horizontalArrangement = Arrangement.SpaceBetween
            ) {
                Text("Raw Events (${log.size})", style = MaterialTheme.typography.titleMedium)
            }
            Spacer(Modifier.height(6.dp))

            val listState = rememberLazyListState()
            LaunchedEffect(log.size) {
                if (log.isNotEmpty()) {
                    listState.scrollToItem(log.size - 1)
                }
            }

            Card(modifier = Modifier.fillMaxWidth()) {
                LazyColumn(
                    state = listState,
                    modifier = Modifier
                        .fillMaxWidth()
                        .heightIn(min = 180.dp, max = 360.dp)
                        .padding(8.dp)
                ) {
                    if (log.isEmpty()) {
                        item {
                            Text(
                                "No events yet. Press any button or move any axis on the controller.",
                                style = MaterialTheme.typography.bodySmall,
                                color = MaterialTheme.colorScheme.onSurfaceVariant
                            )
                        }
                    } else {
                        items(log) { line ->
                            Text(
                                text = line,
                                fontFamily = FontFamily.Monospace,
                                fontSize = 10.sp,
                                color = MaterialTheme.colorScheme.onSurface
                            )
                        }
                    }
                }
            }
        }
    }
}

@Composable
private fun ControllerDiagram(pressed: Set<GamepadButton>) {
    val btnSize = 34.dp
    val smallBtn = 28.dp
    val pillW = 38.dp
    val pillH = 22.dp

    Card(modifier = Modifier.fillMaxWidth()) {
        BoxWithConstraints(
            modifier = Modifier
                .fillMaxWidth()
                .height(200.dp)
                .padding(8.dp)
        ) {
            val w = maxWidth
            val h = maxHeight

            // --- Shoulder buttons ---
            // L2 / R2 (top row)
            ControllerButton("L2", GamepadButton.L2 in pressed, pillW, pillH, RoundedCornerShape(4.dp),
                x = w * 0.08f, y = h * 0.02f)
            ControllerButton("R2", GamepadButton.R2 in pressed, pillW, pillH, RoundedCornerShape(4.dp),
                x = w - w * 0.08f - pillW, y = h * 0.02f)
            // L1 / R1
            ControllerButton("L1", GamepadButton.L1 in pressed, pillW, pillH, RoundedCornerShape(4.dp),
                x = w * 0.08f, y = h * 0.15f)
            ControllerButton("R1", GamepadButton.R1 in pressed, pillW, pillH, RoundedCornerShape(4.dp),
                x = w - w * 0.08f - pillW, y = h * 0.15f)

            // --- D-Pad (left side) ---
            val dpadCx = w * 0.18f
            val dpadCy = h * 0.50f
            val dpadOff = btnSize * 0.85f
            ControllerButton("↑", GamepadButton.DPAD_UP in pressed, smallBtn, smallBtn, CircleShape,
                x = dpadCx - smallBtn / 2, y = dpadCy - dpadOff - smallBtn / 2)
            ControllerButton("↓", GamepadButton.DPAD_DOWN in pressed, smallBtn, smallBtn, CircleShape,
                x = dpadCx - smallBtn / 2, y = dpadCy + dpadOff - smallBtn / 2)
            ControllerButton("←", GamepadButton.DPAD_LEFT in pressed, smallBtn, smallBtn, CircleShape,
                x = dpadCx - dpadOff - smallBtn / 2, y = dpadCy - smallBtn / 2)
            ControllerButton("→", GamepadButton.DPAD_RIGHT in pressed, smallBtn, smallBtn, CircleShape,
                x = dpadCx + dpadOff - smallBtn / 2, y = dpadCy - smallBtn / 2)

            // --- Face buttons (right side, diamond) ---
            val faceCx = w * 0.82f
            val faceCy = h * 0.50f
            val faceOff = btnSize * 0.85f
            ControllerButton("△", GamepadButton.FACE_TOP in pressed, btnSize, btnSize, CircleShape,
                x = faceCx - btnSize / 2, y = faceCy - faceOff - btnSize / 2)
            ControllerButton("✕", GamepadButton.FACE_BOTTOM in pressed, btnSize, btnSize, CircleShape,
                x = faceCx - btnSize / 2, y = faceCy + faceOff - btnSize / 2)
            ControllerButton("□", GamepadButton.FACE_LEFT in pressed, btnSize, btnSize, CircleShape,
                x = faceCx - faceOff - btnSize / 2, y = faceCy - btnSize / 2)
            ControllerButton("○", GamepadButton.FACE_RIGHT in pressed, btnSize, btnSize, CircleShape,
                x = faceCx + faceOff - btnSize / 2, y = faceCy - btnSize / 2)

            // --- Center buttons (Select / Start) ---
            val centerY = h * 0.38f
            ControllerButton("SL", GamepadButton.SELECT in pressed, pillW, pillH, RoundedCornerShape(4.dp),
                x = w * 0.5f - pillW - 4.dp, y = centerY)
            ControllerButton("ST", GamepadButton.START in pressed, pillW, pillH, RoundedCornerShape(4.dp),
                x = w * 0.5f + 4.dp, y = centerY)

            // --- Stick clicks (L3 / R3) ---
            val stickY = h * 0.78f
            ControllerButton("L3", GamepadButton.L3 in pressed, btnSize, btnSize, CircleShape,
                x = w * 0.33f - btnSize / 2, y = stickY - btnSize / 2)
            ControllerButton("R3", GamepadButton.R3 in pressed, btnSize, btnSize, CircleShape,
                x = w * 0.67f - btnSize / 2, y = stickY - btnSize / 2)

            // --- Genesis extras (bottom center, only visible when pressed) ---
            val extraY = h * 0.62f
            if (GamepadButton.MODE in pressed || GamepadButton.Z_BUTTON in pressed || GamepadButton.C_BUTTON in pressed) {
                ControllerButton("MD", GamepadButton.MODE in pressed, smallBtn, smallBtn, CircleShape,
                    x = w * 0.42f - smallBtn / 2, y = extraY)
                ControllerButton("Z", GamepadButton.Z_BUTTON in pressed, smallBtn, smallBtn, CircleShape,
                    x = w * 0.50f - smallBtn / 2, y = extraY)
                ControllerButton("C", GamepadButton.C_BUTTON in pressed, smallBtn, smallBtn, CircleShape,
                    x = w * 0.58f - smallBtn / 2, y = extraY)
            }
        }
    }
}

@Composable
private fun ControllerButton(
    label: String,
    active: Boolean,
    width: Dp,
    height: Dp,
    shape: androidx.compose.ui.graphics.Shape,
    x: Dp,
    y: Dp
) {
    val density = LocalDensity.current
    val bg = if (active) MaterialTheme.colorScheme.primary else Color.Transparent
    val fg = if (active) MaterialTheme.colorScheme.onPrimary else MaterialTheme.colorScheme.onSurfaceVariant
    val borderColor = if (active) MaterialTheme.colorScheme.primary else MaterialTheme.colorScheme.outlineVariant

    Box(
        modifier = Modifier
            .offset {
                IntOffset(
                    with(density) { x.roundToPx() },
                    with(density) { y.roundToPx() }
                )
            }
            .size(width, height)
            .border(1.5.dp, borderColor, shape)
            .background(bg, shape),
        contentAlignment = Alignment.Center
    ) {
        Text(
            text = label,
            color = fg,
            fontSize = 10.sp,
            fontWeight = if (active) FontWeight.Bold else FontWeight.Normal
        )
    }
}

@Composable
private fun UsbDeviceRow(d: UsbDeviceInfo) {
    val classLabel = when (d.deviceClass) {
        3 -> "HID"
        0 -> "use-iface"
        0xFF -> "VENDOR (xinput?)"
        9 -> "hub"
        else -> "class-${d.deviceClass}"
    }
    val isHid = d.deviceClass == 3 || d.interfaces.any { it.interfaceClass == 3 }
    Column {
        Text(
            d.productName ?: d.deviceName,
            fontWeight = FontWeight.SemiBold,
            style = MaterialTheme.typography.bodyMedium
        )
        Text(
            "v=0x${"%04x".format(d.vendorId)}  p=0x${"%04x".format(d.productId)}  " +
                "devClass=${d.deviceClass} ($classLabel)  " +
                if (isHid) "HID ✓" else "NO HID",
            fontFamily = FontFamily.Monospace,
            fontSize = 11.sp,
            color = if (isHid)
                MaterialTheme.colorScheme.primary
            else
                MaterialTheme.colorScheme.error
        )
        d.manufacturerName?.let {
            Text(
                "mfr: $it",
                fontSize = 10.sp,
                color = MaterialTheme.colorScheme.onSurfaceVariant
            )
        }
        d.interfaces.forEach { i ->
            val iLabel = when (i.interfaceClass) {
                3 -> "HID"
                0xFF -> "VENDOR"
                9 -> "hub"
                else -> "class-${i.interfaceClass}"
            }
            Text(
                "  iface#${i.number}  class=${i.interfaceClass} ($iLabel)  sub=${i.interfaceSubclass}  proto=${i.interfaceProtocol}  ep=${i.endpointCount}",
                fontFamily = FontFamily.Monospace,
                fontSize = 10.sp,
                color = MaterialTheme.colorScheme.onSurfaceVariant
            )
        }
    }
}

@Composable
private fun AxisRow(label: String, x: Float, y: Float) {
    Row(
        modifier = Modifier
            .fillMaxWidth()
            .padding(vertical = 4.dp)
    ) {
        Text(label, modifier = Modifier.width(110.dp), style = MaterialTheme.typography.bodyMedium)
        Text(
            "x=${"%+.2f".format(x)}  y=${"%+.2f".format(y)}",
            fontFamily = FontFamily.Monospace,
            style = MaterialTheme.typography.bodyMedium
        )
    }
}

