package com.example.m20_gamepad.ui

import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.Arrangement
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.WindowInsets
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.navigationBars
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.statusBars
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.layout.windowInsetsPadding
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Info
import androidx.compose.material.icons.filled.Settings
import androidx.compose.material3.Button
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.SnackbarHost
import androidx.compose.material3.SnackbarHostState
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.getValue
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.layout.ContentScale
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import androidx.lifecycle.viewmodel.compose.viewModel
import androidx.lifecycle.viewmodel.initializer
import androidx.lifecycle.viewmodel.viewModelFactory
import com.erz.joysticklibrary.Joystick
import com.erz.joysticklibrary.JoystickType
import com.example.m20_gamepad.R
import com.example.m20_gamepad.data.SettingsRepository
import com.example.m20_gamepad.network.ProtocolClient
import com.example.m20_gamepad.network.models.ControlCommands
import com.example.m20_gamepad.network.models.LedStatus
import com.example.m20_gamepad.ui.components.StatusPanel
import com.example.m20_gamepad.video.RtspVideoPlayer

// 半透明覆盖层颜色
private val OverlayBg = Color(0x88000000)
private val OverlayText = Color.White

/**
 * 主界面：RTSP 视频背景 + 双摇杆覆盖层 + 状态栏 + 控制按钮。
 *
 * @param repository 应用级设置仓库（注入 MainViewModel）
 * @param onSettingsClick 打开设置界面
 */
@Composable
fun MainScreen(
    repository: SettingsRepository,
    onSettingsClick: () -> Unit,
    viewModel: MainViewModel = viewModel(
        factory = viewModelFactory {
            initializer { MainViewModel(repository) }
        }
    )
) {
    val connectionState by viewModel.connectionState.collectAsStateWithLifecycle()
    val status by viewModel.latestStatus.collectAsStateWithLifecycle()
    val settings by viewModel.settings.collectAsStateWithLifecycle()
    val motionState by viewModel.motionState.collectAsStateWithLifecycle()
    val errorList by viewModel.errorList.collectAsStateWithLifecycle()
    val motionStatus by viewModel.motionStatus.collectAsStateWithLifecycle()
    val deviceTemperature by viewModel.deviceTemperature.collectAsStateWithLifecycle()
    val batteryStatus by viewModel.batteryStatus.collectAsStateWithLifecycle()
    val ledStatus by viewModel.ledStatus.collectAsStateWithLifecycle()
    val lastUpdate by viewModel.lastUpdate.collectAsStateWithLifecycle()
    val actionFeedback by viewModel.actionFeedback.collectAsStateWithLifecycle()

    var statusPanelVisible by remember { mutableStateOf(false) }
    val snackbarHostState = remember { SnackbarHostState() }

    // 指令校验反馈 -> Snackbar
    LaunchedEffect(actionFeedback) {
        val msg = actionFeedback
        if (!msg.isNullOrBlank()) {
            snackbarHostState.showSnackbar(msg)
            viewModel.clearActionFeedback()
        }
    }

    Box(modifier = Modifier.fillMaxSize()) {
        // ---- 底图层（无视频流时显示） ----
        Image(
            painter = painterResource(id = R.drawable.bg1),
            contentDescription = null,
            contentScale = ContentScale.FillBounds,
            modifier = Modifier.fillMaxSize()
        )

        // ---- 视频背景层 ----
        RtspVideoPlayer(
            url = settings.rtspUrl,
            codec = settings.videoCodec,
            resizeMode = settings.videoResizeMode,
            modifier = Modifier.fillMaxSize()
        )

        // ---- 顶部状态栏 ----
        StatusBar(
            connectionState = connectionState,
            status = status,
            onStatusClick = { statusPanelVisible = true },
            onSettingsClick = onSettingsClick,
            modifier = Modifier
                .align(Alignment.TopCenter)
                .windowInsetsPadding(WindowInsets.statusBars)
        )

        // ---- 底部控制区 ----
        BottomControls(
            viewModel = viewModel,
            connectionState = connectionState,
            motionState = motionState,
            ledStatus = ledStatus,
            modifier = Modifier
                .align(Alignment.BottomCenter)
                .windowInsetsPadding(WindowInsets.navigationBars)
        )

        // ---- 状态上报面板 ----
        StatusPanel(
            visible = statusPanelVisible,
            errorList = errorList,
            motionStatus = motionStatus,
            deviceTemperature = deviceTemperature,
            batteryStatus = batteryStatus,
            lastUpdate = lastUpdate,
            onDismiss = { statusPanelVisible = false },
            modifier = Modifier.fillMaxSize()
        )

        // ---- Snackbar ----
        SnackbarHost(
            hostState = snackbarHostState,
            modifier = Modifier.align(Alignment.BottomCenter)
        )
    }
}

// ==================== 顶部状态栏 ====================

@Composable
private fun StatusBar(
    connectionState: ProtocolClient.State,
    status: com.example.m20_gamepad.network.models.StatusReport?,
    onStatusClick: () -> Unit,
    onSettingsClick: () -> Unit,
    modifier: Modifier = Modifier
) {
    Row(
        modifier = modifier
            .fillMaxWidth()
            .background(OverlayBg)
            .padding(horizontal = 12.dp, vertical = 8.dp),
        verticalAlignment = Alignment.CenterVertically,
        horizontalArrangement = Arrangement.SpaceBetween
    ) {
        // 连接状态指示
        ConnectionIndicator(connectionState)

        // 电量 / 运动状态
        Row(
            verticalAlignment = Alignment.CenterVertically,
            horizontalArrangement = Arrangement.spacedBy(16.dp)
        ) {
            status?.batteryStatus?.let {
                val avgLevel = (it.batteryLevelLeft + it.batteryLevelRight) / 2
                StatusChip("电量 ${avgLevel.toInt()}%")
            }
            status?.basicStatus?.let {
                StatusChip(motionStateText(it.motionState))
            }
        }

        // 状态详情 + 设置按钮
        Row(verticalAlignment = Alignment.CenterVertically) {
            IconButton(onClick = onStatusClick) {
                Icon(
                    Icons.Default.Info,
                    contentDescription = "状态",
                    tint = OverlayText
                )
            }
            IconButton(onClick = onSettingsClick) {
                Icon(
                    Icons.Default.Settings,
                    contentDescription = "设置",
                    tint = OverlayText
                )
            }
        }
    }
}

@Composable
private fun ConnectionIndicator(state: ProtocolClient.State) {
    val (color, text) = when (state) {
        ProtocolClient.State.CONNECTED -> Color(0xFF4CAF50) to "已连接"
        ProtocolClient.State.CONNECTING -> Color(0xFFFFC107) to "连接中"
        ProtocolClient.State.TIMEOUT -> Color(0xFFFF9800) to "断线"
        ProtocolClient.State.ERROR -> Color(0xFFF44336) to "错误"
        ProtocolClient.State.DISCONNECTED -> Color(0xFF9E9E9E) to "未连接"
    }
    Row(verticalAlignment = Alignment.CenterVertically) {
        Box(
            modifier = Modifier
                .size(10.dp)
                .background(color, CircleShape)
        )
        Spacer(Modifier.width(6.dp))
        Text(text, color = OverlayText, fontSize = 14.sp)
    }
}

@Composable
private fun StatusChip(text: String) {
    Surface(
        color = Color(0x44000000),
        shape = RoundedCornerShape(12.dp)
    ) {
        Text(
            text = text,
            color = OverlayText,
            fontSize = 13.sp,
            modifier = Modifier.padding(horizontal = 10.dp, vertical = 4.dp)
        )
    }
}

// ==================== 底部控制区 ====================

@Composable
private fun BottomControls(
    viewModel: MainViewModel,
    connectionState: ProtocolClient.State,
    motionState: Int,
    ledStatus: LedStatus?,
    modifier: Modifier = Modifier
) {
    Row(
        modifier = modifier
            .fillMaxWidth()
            .padding(bottom = 16.dp, start = 12.dp, end = 12.dp),
        verticalAlignment = Alignment.Bottom,
        horizontalArrangement = Arrangement.SpaceBetween
    ) {
        // 左摇杆（X/Y 移动）
        Joystick(
            modifier = Modifier.size(180.dp),
            type = JoystickType.EIGHT_AXIS,
            padColor = Color(0x55808080),
            buttonColor = Color(0xCCFFFFFF),
            onMove = { angle, power, _ ->
                viewModel.updateLeftStick(angle, power)
            }
        )

        // 中间控制按钮组
        ControlButtons(
            viewModel = viewModel,
            connectionState = connectionState,
            motionState = motionState,
            ledStatus = ledStatus
        )

        // 右摇杆（Yaw 旋转）
        Joystick(
            modifier = Modifier.size(180.dp),
            type = JoystickType.EIGHT_AXIS,
            padColor = Color(0x55808080),
            buttonColor = Color(0xCCFFFFFF),
            onMove = { angle, power, _ ->
                viewModel.updateRightStick(angle, power)
            }
        )
    }
}

@Composable
private fun ControlButtons(
    viewModel: MainViewModel,
    connectionState: ProtocolClient.State,
    motionState: Int,
    ledStatus: LedStatus?
) {
    val connected = connectionState == ProtocolClient.State.CONNECTED
    val isRlControl = motionState == ControlCommands.MOTION_RL_CONTROL
    var showMore by remember { mutableStateOf(false) }
    val scrollState = rememberScrollState()

    Column(
        horizontalAlignment = Alignment.CenterHorizontally,
        verticalArrangement = Arrangement.spacedBy(6.dp),
        modifier = Modifier
            .verticalScroll(scrollState)
            .padding(top = 4.dp, bottom = 4.dp)
    ) {
        // 连接/断开
        Button(
            onClick = {
                if (connected) viewModel.disconnect() else viewModel.connect()
            },
            colors = ButtonDefaults.buttonColors(
                containerColor = if (connected) Color(0xFFF44336) else Color(0xFF4CAF50)
            ),
            modifier = Modifier.width(110.dp)
        ) {
            Text(if (connected) "断开" else "连接")
        }

        // 运动状态转换
        ControlButton(
            "起立",
            enabled = connected && (motionState == ControlCommands.MOTION_IDLE ||
                    motionState == ControlCommands.MOTION_LIE_DOWN)
        ) {
            viewModel.sendMotionControl(ControlCommands.MOTION_STAND)
        }
        ControlButton(
            "RL控制",
            enabled = connected && motionState == ControlCommands.MOTION_STAND
        ) {
            viewModel.sendMotionControl(ControlCommands.MOTION_RL_CONTROL)
        }
        ControlButton(
            "趴下",
            enabled = connected && motionState != ControlCommands.MOTION_LIE_DOWN
        ) {
            viewModel.sendMotionControl(ControlCommands.MOTION_LIE_DOWN)
        }

        // 步态切换——仅 RL 控制
        if (isRlControl) {
            Row(horizontalArrangement = Arrangement.spacedBy(4.dp)) {
                MiniButton("基础", enabled = isRlControl) {
                    viewModel.sendSwitchGait(ControlCommands.GAIT_BASIC)
                }
                MiniButton("楼梯", enabled = isRlControl) {
                    viewModel.sendSwitchGait(ControlCommands.GAIT_STAIRS)
                }
                MiniButton("平地敏捷", enabled = isRlControl) {
                    viewModel.sendSwitchGait(ControlCommands.GAIT_FLAT_AGILE)
                }
            }
            MiniButton("楼梯敏捷", enabled = isRlControl) {
                viewModel.sendSwitchGait(ControlCommands.GAIT_STAIRS_AGILE)
            }
        }

        // 更多/收起切换
        if (connected) {
            ControlButton(if (showMore) "收起" else "更多", enabled = connected) {
                showMore = !showMore
            }
        }

        // ---- 更多控制（可展开） ----
        if (showMore) {
            Separator()

            // 使用模式
            SectionLabel("使用模式")
            Row(horizontalArrangement = Arrangement.spacedBy(4.dp)) {
                MiniButton("常规") {
                    viewModel.sendSwitchMode(ControlCommands.MODE_NORMAL)
                }
                MiniButton("导航") {
                    viewModel.sendSwitchMode(ControlCommands.MODE_NAVIGATION)
                }
                MiniButton("辅助") {
                    viewModel.sendSwitchMode(ControlCommands.MODE_ASSIST)
                }
            }
            Spacer(Modifier.height(4.dp))

            // 照明
            SectionLabel("照明")
            val frontOn = ledStatus?.front == 1
            val backOn = ledStatus?.back == 1
            Row(horizontalArrangement = Arrangement.spacedBy(4.dp)) {
                LightToggleButton(
                    text = "前灯",
                    isOn = frontOn,
                    enabled = connected
                ) {
                    viewModel.sendLightControl(if (frontOn) 0 else 1, ledStatus?.back ?: 0)
                }
                LightToggleButton(
                    text = "后灯",
                    isOn = backOn,
                    enabled = connected
                ) {
                    viewModel.sendLightControl(ledStatus?.front ?: 0, if (backOn) 0 else 1)
                }
            }
            Spacer(Modifier.height(4.dp))

            // 充电
            SectionLabel("充电")
            Row(horizontalArrangement = Arrangement.spacedBy(4.dp)) {
                MiniButton("开始充电") { viewModel.sendChargeControl(1) }
                MiniButton("结束充电") { viewModel.sendChargeControl(0) }
            }
            Spacer(Modifier.height(4.dp))

            // 休眠
            SectionLabel("休眠")
            Row(horizontalArrangement = Arrangement.spacedBy(4.dp)) {
                MiniButton("进入休眠") { viewModel.sendSleepSettings(true) }
                MiniButton("唤醒") { viewModel.sendSleepSettings(false) }
            }
        }
    }
}

@Composable
private fun ControlButton(
    text: String,
    enabled: Boolean = true,
    onClick: () -> Unit
) {
    Button(
        onClick = onClick,
        enabled = enabled,
        colors = ButtonDefaults.buttonColors(
            containerColor = Color(0x66333333),
            disabledContainerColor = Color(0x33222222)
        ),
        modifier = Modifier.width(110.dp)
    ) {
        Text(text, color = if (enabled) OverlayText else Color(0x88FFFFFF), fontWeight = FontWeight.Medium)
    }
}

@Composable
private fun MiniButton(text: String, enabled: Boolean = true, onClick: () -> Unit) {
    Button(
        onClick = onClick,
        enabled = enabled,
        colors = ButtonDefaults.buttonColors(
            containerColor = Color(0x66333333),
            disabledContainerColor = Color(0x33222222)
        ),
        contentPadding = ButtonDefaults.TextButtonContentPadding,
        modifier = Modifier.height(32.dp)
    ) {
        Text(
            text,
            color = if (enabled) OverlayText else Color(0x88FFFFFF),
            fontSize = 12.sp,
            fontWeight = FontWeight.Normal
        )
    }
}

@Composable
private fun LightToggleButton(
    text: String,
    isOn: Boolean,
    enabled: Boolean = true,
    onClick: () -> Unit
) {
    Button(
        onClick = onClick,
        enabled = enabled,
        colors = ButtonDefaults.buttonColors(
            containerColor = if (isOn) Color(0xCCFFC107) else Color(0x66333333),
            disabledContainerColor = Color(0x33222222)
        ),
        modifier = Modifier.width(110.dp)
    ) {
        Text(
            "$text ${if (isOn) "开" else "关"}",
            color = if (enabled) OverlayText else Color(0x88FFFFFF),
            fontWeight = FontWeight.Medium
        )
    }
}

@Composable
private fun SectionLabel(text: String) {
    Text(
        text,
        color = Color(0xFFB0B0B0),
        fontSize = 11.sp,
        modifier = Modifier.fillMaxWidth()
    )
}

@Composable
private fun Separator() {
    Spacer(Modifier.height(2.dp))
    Box(
        modifier = Modifier
            .width(80.dp)
            .height(1.dp)
            .background(Color(0x44FFFFFF))
    )
    Spacer(Modifier.height(2.dp))
}

// ==================== 辅助函数 ====================

private fun motionStateText(state: Int): String = when (state) {
    0 -> "空闲"
    1 -> "站立"
    2 -> "软急停"
    3 -> "开机阻尼"
    4 -> "趴下"
    17 -> "RL控制"
    else -> "未知($state)"
}