package com.tsmobile.app.ui.components

import android.graphics.BitmapFactory
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.InsertDriveFile
import androidx.compose.material.icons.filled.Check
import androidx.compose.material.icons.filled.ErrorOutline
import androidx.compose.material.icons.filled.Image
import androidx.compose.material.icons.filled.Schedule
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Surface
import androidx.compose.material3.Text
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.asImageBitmap
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.unit.dp
import com.tsmobile.app.data.ChatMessage
import com.tsmobile.app.data.FileDownloadManager
import com.tsmobile.app.data.FileMessageMeta
import com.tsmobile.app.data.MessageDeliveryState
import com.tsmobile.app.data.MessageType
import com.tsmobile.app.data.Repository
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch
import kotlinx.coroutines.withContext
import java.text.SimpleDateFormat
import java.util.Date
import java.util.Locale

/**
 * 单条消息组件。
 * 区分自己/他人消息，显示发送者名称、时间和送达状态。
 * 支持文本消息和文件/图片消息的渲染。
 */
@Composable
fun MessageItem(message: ChatMessage) {
    // 系统消息：居中显示，无气泡
    if (message.messageType == MessageType.SYSTEM) {
        val timeText = remember(message.timestamp) {
            SimpleDateFormat("HH:mm", Locale.getDefault()).format(Date(message.timestamp))
        }
        Row(
            modifier = Modifier
                .fillMaxWidth()
                .padding(vertical = 6.dp, horizontal = 16.dp),
            horizontalArrangement = Arrangement.Center,
            verticalAlignment = Alignment.CenterVertically,
        ) {
            Text(
                text = message.content,
                style = MaterialTheme.typography.labelSmall,
                color = MaterialTheme.colorScheme.onSurfaceVariant,
            )
            Spacer(Modifier.width(6.dp))
            Text(
                text = timeText,
                style = MaterialTheme.typography.labelSmall,
                color = MaterialTheme.colorScheme.onSurfaceVariant.copy(alpha = 0.6f),
            )
        }
        return
    }

    val timeText = remember(message.timestamp) {
        SimpleDateFormat("HH:mm", Locale.getDefault())
            .format(Date(message.timestamp))
    }
    val bubbleColor = if (message.isSelf) {
        MaterialTheme.colorScheme.primaryContainer
    } else {
        MaterialTheme.colorScheme.surfaceContainerHigh
    }
    val bubbleContentColor = if (message.isSelf) {
        MaterialTheme.colorScheme.onPrimaryContainer
    } else {
        MaterialTheme.colorScheme.onSurface
    }

    Column(
        modifier = Modifier
            .fillMaxWidth()
            .padding(vertical = 4.dp),
        horizontalAlignment = if (message.isSelf) Alignment.End else Alignment.Start
    ) {
        // 发送者名称 + 时间
        Row(
            verticalAlignment = Alignment.CenterVertically,
            horizontalArrangement = if (message.isSelf) Arrangement.End else Arrangement.Start,
            modifier = Modifier.fillMaxWidth()
        ) {
            if (!message.isSelf) {
                Text(
                    text = message.senderName,
                    style = MaterialTheme.typography.labelMedium,
                    color = MaterialTheme.colorScheme.primary
                )
                Spacer(Modifier.width(8.dp))
            }
            Text(
                text = timeText,
                style = MaterialTheme.typography.labelSmall,
                color = MaterialTheme.colorScheme.onSurfaceVariant
            )
            if (message.isSelf) {
                Spacer(Modifier.width(8.dp))
                Text(
                    text = message.senderName,
                    style = MaterialTheme.typography.labelMedium,
                    color = MaterialTheme.colorScheme.primary
                )
            }
        }

        Spacer(Modifier.height(4.dp))

        // 消息气泡 + 送达状态
        Row(
            verticalAlignment = Alignment.Bottom,
            horizontalArrangement = if (message.isSelf) Arrangement.End else Arrangement.Start,
            modifier = Modifier.fillMaxWidth()
        ) {
            if (message.isSelf) {
                // 送达状态指示（自己消息左侧）
                DeliveryStateIndicator(message.deliveryState)
                Spacer(Modifier.width(6.dp))
            }

            if (message.fileMeta != null) {
                // 文件/图片消息气泡
                android.util.Log.d("MessageItem", "Rendering file message: fileName=${message.fileMeta.fileName}, isImage=${message.fileMeta.isImage}, isMyTS=${message.fileMeta.isMyTS}")
                FileMessageBubble(
                    fileMeta = message.fileMeta,
                    bubbleColor = bubbleColor,
                    contentColor = bubbleContentColor
                )
            } else {
                // 普通文本消息气泡
                Surface(
                    shape = if (message.isSelf) {
                        RoundedCornerShape(20.dp, 20.dp, 4.dp, 20.dp)
                    } else {
                        RoundedCornerShape(20.dp, 20.dp, 20.dp, 4.dp)
                    },
                    color = bubbleColor,
                    contentColor = bubbleContentColor,
                    modifier = Modifier.widthIn(max = 300.dp),
                    tonalElevation = 1.dp
                ) {
                    Text(
                        text = message.content,
                        style = MaterialTheme.typography.bodyMedium,
                        modifier = Modifier.padding(horizontal = 16.dp, vertical = 10.dp)
                    )
                }
            }
        }
    }
}

/**
 * 文件/图片消息气泡。
 * 图片消息自动下载并显示缩略图，其他文件显示文件名和大小。
 */
@Composable
private fun FileMessageBubble(
    fileMeta: FileMessageMeta,
    bubbleColor: Color,
    contentColor: Color
) {
    val context = LocalContext.current
    val scope = rememberCoroutineScope()

    // 图片下载状态
    var imageBitmap by remember { mutableStateOf<androidx.compose.ui.graphics.ImageBitmap?>(null) }
    var isLoading by remember { mutableStateOf(false) }
    var loadFailed by remember { mutableStateOf(false) }

    // 频道 ID（用于文件传输）
    val currentChannelId by Repository.currentChannelId.collectAsState()

    // 当文件是图片时，自动触发下载
    LaunchedEffect(fileMeta.fileId, fileMeta.isImage) {
        if (!fileMeta.isImage) return@LaunchedEffect

        // 先检查缓存
        val cached = FileDownloadManager.getCachedFile(context, fileMeta.fileId)
        if (cached != null) {
            withContext(Dispatchers.IO) {
                val bmp = BitmapFactory.decodeFile(cached.absolutePath)
                if (bmp != null) {
                    imageBitmap = bmp.asImageBitmap()
                    return@withContext
                }
            }
            if (imageBitmap != null) return@LaunchedEffect
        }

        // 缓存未命中，下载
        isLoading = true
        loadFailed = false
        scope.launch {
            val file = if (fileMeta.isMyTS) {
                // MyTS 文件：通过 HTTP 从独立服务器下载
                FileDownloadManager.downloadMyTSFile(
                    context = context,
                    fileId = fileMeta.fileId,
                    fileName = fileMeta.fileName,
                    chatUserId = fileMeta.chatUserId
                )
            } else {
                // 普通频道文件：通过 TeamSpeak 文件传输协议下载
                FileDownloadManager.downloadAndCache(
                    context = context,
                    channelID = currentChannelId,
                    fileId = fileMeta.fileId,
                    fileName = fileMeta.fileName
                )
            }
            isLoading = false
            if (file != null) {
                withContext(Dispatchers.IO) {
                    val bmp = BitmapFactory.decodeFile(file.absolutePath)
                    if (bmp != null) {
                        imageBitmap = bmp.asImageBitmap()
                    } else {
                        loadFailed = true
                    }
                }
            } else {
                loadFailed = true
            }
        }
    }

    android.util.Log.d("FileMessageBubble", "Composing: isImage=${fileMeta.isImage}, isMyTS=${fileMeta.isMyTS}")
    Surface(
        shape = RoundedCornerShape(20.dp),
        color = bubbleColor,
        contentColor = contentColor,
        modifier = Modifier.widthIn(max = 300.dp),
        tonalElevation = 1.dp
    ) {
        android.util.Log.d("FileMessageBubble", "Inside Surface: isImage=${fileMeta.isImage}")
        if (fileMeta.isImage) {
            // 图片消息
            Column(
                modifier = Modifier.padding(10.dp),
                horizontalAlignment = Alignment.CenterHorizontally
            ) {
                if (imageBitmap != null) {
                    // 图片加载成功，显示图片
                    Image(
                        bitmap = imageBitmap!!,
                        contentDescription = fileMeta.fileName,
                        modifier = Modifier
                            .sizeIn(maxWidth = 260.dp, maxHeight = 220.dp)
                            .clip(RoundedCornerShape(12.dp)),
                        contentScale = ContentScale.Fit
                    )
                } else {
                    // 图片加载中或失败
                    Box(
                        modifier = Modifier
                            .size(120.dp)
                            .clip(RoundedCornerShape(12.dp))
                            .background(MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.5f)),
                        contentAlignment = Alignment.Center
                    ) {
                        when {
                            isLoading -> {
                                CircularProgressIndicator(
                                    modifier = Modifier.size(32.dp),
                                    strokeWidth = 3.dp,
                                    color = MaterialTheme.colorScheme.primary
                                )
                            }
                            loadFailed -> {
                                Icon(
                                    imageVector = Icons.Default.Image,
                                    contentDescription = "加载失败",
                                    modifier = Modifier.size(48.dp),
                                    tint = MaterialTheme.colorScheme.error.copy(alpha = 0.6f)
                                )
                            }
                            else -> {
                                Icon(
                                    imageVector = Icons.Default.Image,
                                    contentDescription = "图片",
                                    modifier = Modifier.size(48.dp),
                                    tint = MaterialTheme.colorScheme.onSurfaceVariant.copy(alpha = 0.6f)
                                )
                            }
                        }
                    }
                }

                Spacer(Modifier.height(6.dp))

                // 文件名 + 大小
                Text(
                    text = fileMeta.fileName,
                    style = MaterialTheme.typography.labelMedium,
                    color = contentColor.copy(alpha = 0.8f),
                    maxLines = 1
                )
                Text(
                    text = fileMeta.formattedSize,
                    style = MaterialTheme.typography.labelSmall,
                    color = contentColor.copy(alpha = 0.6f)
                )
            }
        } else {
            // 非图片文件：显示文件图标 + 文件名 + 大小
            Row(
                modifier = Modifier.padding(horizontal = 14.dp, vertical = 12.dp),
                verticalAlignment = Alignment.CenterVertically
            ) {
                Surface(
                    shape = MaterialTheme.shapes.medium,
                    color = MaterialTheme.colorScheme.primary.copy(alpha = 0.12f),
                    contentColor = MaterialTheme.colorScheme.primary
                ) {
                    Icon(
                        imageVector = Icons.AutoMirrored.Filled.InsertDriveFile,
                        contentDescription = "文件",
                        modifier = Modifier.padding(8.dp).size(24.dp)
                    )
                }
                Spacer(Modifier.width(10.dp))
                Column {
                    Text(
                        text = fileMeta.fileName,
                        style = MaterialTheme.typography.bodySmall,
                        color = contentColor,
                        maxLines = 1
                    )
                    Text(
                        text = fileMeta.formattedSize,
                        style = MaterialTheme.typography.labelSmall,
                        color = contentColor.copy(alpha = 0.6f)
                    )
                }
            }
        }
    }
}

/**
 * 送达状态指示器。
 * 只在自己发送的消息上显示：
 * - PENDING：时钟图标（灰色）
 * - SENT：双勾图标（默认色）
 * - FAILED：感叹号图标（红色）
 */
@Composable
private fun DeliveryStateIndicator(state: MessageDeliveryState) {
    when (state) {
        MessageDeliveryState.PENDING -> {
            Icon(
                imageVector = Icons.Default.Schedule,
                contentDescription = "发送中",
                modifier = Modifier.size(14.dp),
                tint = MaterialTheme.colorScheme.onSurfaceVariant.copy(alpha = 0.5f)
            )
        }
        MessageDeliveryState.SENT -> {
            Icon(
                imageVector = Icons.Default.Check,
                contentDescription = "已送达",
                modifier = Modifier.size(14.dp),
                tint = MaterialTheme.colorScheme.primary.copy(alpha = 0.6f)
            )
        }
        MessageDeliveryState.FAILED -> {
            Icon(
                imageVector = Icons.Default.ErrorOutline,
                contentDescription = "发送失败",
                modifier = Modifier.size(14.dp),
                tint = MaterialTheme.colorScheme.error
            )
        }
    }
}
