package com.tsmobile.app.ui.screens

import androidx.compose.foundation.layout.*
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Modifier
import androidx.compose.foundation.layout.imePadding
import androidx.compose.ui.platform.LocalFocusManager
import com.tsmobile.app.data.ChannelInfo
import com.tsmobile.app.ui.components.ChannelDetailCard
import com.tsmobile.app.ui.components.ChatHeader
import com.tsmobile.app.ui.components.MessageInputBar
import com.tsmobile.app.ui.components.MessageList
import com.tsmobile.app.ui.components.PokeDialog
import com.tsmobile.app.ui.components.VoiceCard
import com.tsmobile.app.ui.components.VoiceControlBar
import com.tsmobile.app.viewmodel.ChannelViewModel
import com.tsmobile.app.viewmodel.ChatViewModel
import com.tsmobile.app.viewmodel.ServerViewModel
import com.tsmobile.app.viewmodel.VoiceViewModel

/**
 * 聊天页。
 * 三段式布局：头部 + 消息列表 + 输入区。
 */
@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun ChatScreen(
    chatViewModel: ChatViewModel,
    channelViewModel: ChannelViewModel,
    voiceViewModel: VoiceViewModel,
    serverViewModel: ServerViewModel,
    onNavigateBack: () -> Unit,
    onOpenChannelDetail: (channelId: String) -> Unit
) {
    val messages by chatViewModel.messages.collectAsState()
    val sendState by chatViewModel.sendState.collectAsState()
    val currentChannelId by channelViewModel.currentChannelId.collectAsState()
    val channels by channelViewModel.channels.collectAsState()
    val channelClients by channelViewModel.channelClients.collectAsState()
    var showVoiceCard by remember { mutableStateOf(false) }

    // 语音卡 Poke 状态（长按成员 → PokeDialog）
    var voiceCardPokeTarget by remember { mutableStateOf<Pair<Int, String>?>(null) }

    // 频道详情卡状态
    val showChannelDetailCard by channelViewModel.showChannelDetailCard.collectAsState()
    val channelDetail by channelViewModel.channelDetailInfo.collectAsState()

    val currentChannel = channels.find { it.id == currentChannelId }
    val clients = channelClients[currentChannelId] ?: emptyList()
    val focusManager = LocalFocusManager.current

    Column(
        modifier = Modifier
            .fillMaxSize()
            .systemBarsPadding()
            .imePadding(),
    ) {
        // 头部：返回按钮 + 频道名 + 频道详情入口
        ChatHeader(
            channelName = currentChannel?.name ?: "",
            memberCount = clients.size,
            onBack = onNavigateBack,
            onChannelDetail = {
                currentChannel?.let { onOpenChannelDetail(it.id) }
            }
        )

        // 中部：消息列表（占满剩余空间）
        MessageList(
            messages = messages,
            modifier = Modifier
                .weight(1f)
                .fillMaxWidth()
        )

        // 中部-底部：消息输入区（随键盘上抬）
        MessageInputBar(
            sendState = sendState,
            onSendMessage = { text -> chatViewModel.sendMessage(text) },
            modifier = Modifier.fillMaxWidth()
        )

        // 底部：语音控制栏（固定在底部，不受键盘影响）
        VoiceControlBar(
            voiceViewModel = voiceViewModel,
            onExpand = {
                focusManager.clearFocus()
                voiceViewModel.openVoiceCard()
                showVoiceCard = true
            },
        )
    }

    // 语音卡弹窗（BottomSheet）
    if (showVoiceCard) {
        ModalBottomSheet(
            onDismissRequest = {
                showVoiceCard = false
                voiceViewModel.closeVoiceCard()
            },
        ) {
            VoiceCard(
                voiceViewModel = voiceViewModel,
                channelViewModel = channelViewModel,
                onDismiss = {
                    showVoiceCard = false
                    voiceViewModel.closeVoiceCard()
                },
                onPokeClient = { clientId, message ->
                    serverViewModel.pokeClient(clientId, message)
                },
            )
        }
    }

    // Poke 弹窗（语音卡成员长按）已经在 VoiceCard 内部处理

    // 频道详情卡弹窗（BottomSheet）
    if (showChannelDetailCard) {
        ModalBottomSheet(
            onDismissRequest = { channelViewModel.closeChannelDetailCard() },
        ) {
            ChannelDetailCard(
                channelDetail = channelDetail,
                isCurrentChannel = channelDetail?.id == currentChannelId,
                onSwitchChannel = {
                    channelViewModel.closeChannelDetailCard()
                },
                onDismiss = { channelViewModel.closeChannelDetailCard() },
            )
        }
    }
}
