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

import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.gestures.detectDragGestures
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.offset
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.ArrowBack
import androidx.compose.material.icons.filled.RestartAlt
import androidx.compose.material3.Button
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.Slider
import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBar
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableFloatStateOf
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.input.pointer.pointerInput
import androidx.compose.ui.platform.LocalDensity
import androidx.compose.ui.unit.IntOffset
import androidx.compose.ui.unit.dp
import com.lazy.emulate.emulation.ConsoleType
import com.lazy.emulate.input.ButtonPosition
import com.lazy.emulate.input.ControllerLayout
import com.lazy.emulate.input.GamepadButton
import kotlin.math.roundToInt

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun ControllerLayoutScreen(
    consoleType: ConsoleType,
    onBack: () -> Unit
) {
    var layout by remember { mutableStateOf(ControllerLayout.defaultForConsole(consoleType)) }
    var opacity by remember { mutableFloatStateOf(layout.opacity) }

    Scaffold(
        topBar = {
            TopAppBar(
                title = { Text("${consoleType.displayName} Layout") },
                navigationIcon = {
                    IconButton(onClick = onBack) {
                        Icon(Icons.AutoMirrored.Filled.ArrowBack, contentDescription = "Back")
                    }
                },
                actions = {
                    IconButton(onClick = {
                        layout = ControllerLayout.defaultForConsole(consoleType)
                        opacity = layout.opacity
                    }) {
                        Icon(Icons.Default.RestartAlt, contentDescription = "Reset Layout")
                    }
                }
            )
        }
    ) { padding ->
        Column(
            modifier = Modifier
                .fillMaxSize()
                .padding(padding)
        ) {
            // Preview area
            BoxWithConstraints(
                modifier = Modifier
                    .fillMaxWidth()
                    .weight(1f)
                    .background(Color.Black)
            ) {
                val screenWidth = constraints.maxWidth.toFloat()
                val screenHeight = constraints.maxHeight.toFloat()
                val density = LocalDensity.current

                // Draggable buttons
                layout.buttons.forEach { buttonPos ->
                    DraggableButton(
                        buttonPosition = buttonPos,
                        consoleType = consoleType,
                        screenWidth = screenWidth,
                        screenHeight = screenHeight,
                        opacity = opacity,
                        onPositionChanged = { newX, newY ->
                            layout = layout.copy(
                                buttons = layout.buttons.map {
                                    if (it.button == buttonPos.button) {
                                        it.copy(x = newX / screenWidth, y = newY / screenHeight)
                                    } else it
                                }
                            )
                        }
                    )
                }

                // Info overlay
                Text(
                    text = "Drag buttons to reposition",
                    style = MaterialTheme.typography.bodyMedium,
                    color = Color.White.copy(alpha = 0.5f),
                    modifier = Modifier
                        .align(Alignment.TopCenter)
                        .padding(16.dp)
                )
            }

            // Controls
            Column(
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(16.dp)
            ) {
                Text("Opacity", style = MaterialTheme.typography.bodyLarge)
                Slider(
                    value = opacity,
                    onValueChange = {
                        opacity = it
                        layout = layout.copy(opacity = it)
                    },
                    valueRange = 0.1f..1.0f
                )

                Spacer(modifier = Modifier.height(12.dp))

                Row {
                    OutlinedButton(
                        onClick = {
                            layout = ControllerLayout.defaultForConsole(consoleType)
                            opacity = layout.opacity
                        },
                        modifier = Modifier.weight(1f)
                    ) {
                        Text("Reset")
                    }
                    Spacer(modifier = Modifier.width(12.dp))
                    Button(
                        onClick = {
                            // TODO: Save layout to DataStore
                            onBack()
                        },
                        modifier = Modifier.weight(1f)
                    ) {
                        Text("Save")
                    }
                }
            }
        }
    }
}

@Composable
private fun DraggableButton(
    buttonPosition: ButtonPosition,
    consoleType: ConsoleType,
    screenWidth: Float,
    screenHeight: Float,
    opacity: Float,
    onPositionChanged: (Float, Float) -> Unit
) {
    val density = LocalDensity.current
    val sizePx = buttonPosition.size * screenWidth
    var offsetX by remember { mutableFloatStateOf(buttonPosition.x * screenWidth) }
    var offsetY by remember { mutableFloatStateOf(buttonPosition.y * screenHeight) }

    val sizeDp = with(density) { sizePx.toDp() }

    Box(
        modifier = Modifier
            .offset { IntOffset((offsetX - sizePx / 2).roundToInt(), (offsetY - sizePx / 2).roundToInt()) }
            .size(sizeDp)
            .border(2.dp, Color.White.copy(alpha = opacity), CircleShape)
            .background(Color.White.copy(alpha = opacity * 0.2f), CircleShape)
            .pointerInput(Unit) {
                detectDragGestures { _, dragAmount ->
                    offsetX = (offsetX + dragAmount.x).coerceIn(0f, screenWidth)
                    offsetY = (offsetY + dragAmount.y).coerceIn(0f, screenHeight)
                    onPositionChanged(offsetX, offsetY)
                }
            },
        contentAlignment = Alignment.Center
    ) {
        Text(
            text = buttonPosition.button.toLabel(consoleType),
            style = MaterialTheme.typography.labelSmall,
            color = Color.White.copy(alpha = opacity)
        )
    }
}

private fun GamepadButton.toLabel(consoleType: ConsoleType): String {
    // Shared labels for non-face buttons
    val shared = when (this) {
        GamepadButton.DPAD_UP -> "Up"
        GamepadButton.DPAD_DOWN -> "Dn"
        GamepadButton.DPAD_LEFT -> "Lt"
        GamepadButton.DPAD_RIGHT -> "Rt"
        GamepadButton.L1 -> "L1"
        GamepadButton.R1 -> "R1"
        GamepadButton.L2 -> "L2"
        GamepadButton.R2 -> "R2"
        GamepadButton.L3 -> "L3"
        GamepadButton.R3 -> "R3"
        GamepadButton.START -> "ST"
        GamepadButton.SELECT -> "SL"
        GamepadButton.MODE -> "MD"
        GamepadButton.Z_BUTTON -> "Z"
        GamepadButton.C_BUTTON -> "C"
        else -> null
    }
    if (shared != null) return shared

    return when (consoleType) {
        ConsoleType.PS1, ConsoleType.PS2 -> when (this) {
            GamepadButton.FACE_BOTTOM -> "X"
            GamepadButton.FACE_RIGHT -> "O"
            GamepadButton.FACE_LEFT -> "[]"
            GamepadButton.FACE_TOP -> "/\\"
            else -> ""
        }
        ConsoleType.NES -> when (this) {
            GamepadButton.FACE_BOTTOM -> "A"
            GamepadButton.FACE_RIGHT -> "B"
            GamepadButton.FACE_LEFT -> "A"
            GamepadButton.FACE_TOP -> "B"
            else -> ""
        }
        ConsoleType.SNES -> when (this) {
            GamepadButton.FACE_BOTTOM -> "B"
            GamepadButton.FACE_RIGHT -> "A"
            GamepadButton.FACE_LEFT -> "Y"
            GamepadButton.FACE_TOP -> "X"
            else -> ""
        }
        ConsoleType.N64 -> when (this) {
            GamepadButton.FACE_BOTTOM -> "A"
            GamepadButton.FACE_RIGHT -> "B"
            GamepadButton.FACE_LEFT -> "A"
            GamepadButton.FACE_TOP -> "B"
            else -> ""
        }
        ConsoleType.GENESIS -> when (this) {
            GamepadButton.FACE_BOTTOM -> "A"
            GamepadButton.FACE_RIGHT -> "B"
            GamepadButton.FACE_LEFT -> "X"
            GamepadButton.FACE_TOP -> "Y"
            else -> ""
        }
    }
}
