package com.stand.standapp.ui.chat.components

import androidx.compose.foundation.background
import androidx.compose.foundation.gestures.detectDragGestures
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.lazy.rememberLazyListState
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Close
import androidx.compose.material.icons.filled.Menu
import androidx.compose.material.icons.filled.Send
import androidx.compose.material3.*
import androidx.compose.runtime.*
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.unit.dp
import com.stand.standapp.ui.chat.model.ChatMessage

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun ChatArea(
    messages: List<ChatMessage>,
    onSendMessage: (String) -> Unit,
    onOpenDrawer: () -> Unit,
    onClose: () -> Unit,
    modifier: Modifier = Modifier,
    onDrag: (Float, Float) -> Unit = { _, _ -> },
    onCancelStreaming: () -> Unit = {}
) {
    var inputText by remember { mutableStateOf("") }
    val listState = rememberLazyListState()

    LaunchedEffect(messages.size) {
        if (messages.isNotEmpty()) {
            listState.scrollToItem(messages.size - 1, Int.MAX_VALUE)
        }
    }

    val isAnyStreaming = remember(messages) { messages.any { it.isStreaming } }
    if (isAnyStreaming) {
        val totalLength = messages.map { it.content.length }.sum()
        LaunchedEffect(totalLength) {
            if (messages.isNotEmpty()) {
                listState.scrollToItem(messages.size - 1, Int.MAX_VALUE)
            }
        }
    }

    Column(modifier = Modifier.fillMaxSize().background(Color.White)) {
        TopAppBar(
            title = { Text("AI 助手", style = MaterialTheme.typography.titleMedium) },
            navigationIcon = {
                IconButton(onClick = onOpenDrawer) {
                    Icon(Icons.Default.Menu, contentDescription = "Menu")
                }
            },
            actions = {
                TextButton(onClick = onClose) { Text("关闭") }
            },
            colors = TopAppBarDefaults.topAppBarColors(containerColor = Color(0xFFF3F4F6)),
            modifier = Modifier.pointerInput(Unit) {
                detectDragGestures(
                    onDragStart = { },
                    onDragEnd = { },
                    onDragCancel = { },
                    onDrag = { change, dragAmount ->
                        change.consume()
                        onDrag(dragAmount.x, dragAmount.y)
                    }
                )
            }
        )

        LazyColumn(
            state = listState,
            modifier = Modifier.weight(1f).fillMaxWidth().padding(horizontal = 12.dp),
            contentPadding = PaddingValues(vertical = 12.dp),
            verticalArrangement = Arrangement.spacedBy(8.dp)
        ) {
            items(messages, key = { it.id }) { msg ->
                val isUser = msg.role == ChatMessage.Role.USER
                Box(
                    modifier = Modifier.fillMaxWidth(),
                    contentAlignment = if (isUser) Alignment.CenterEnd else Alignment.CenterStart
                ) {
                    Surface(
                        shape = RoundedCornerShape(12.dp),
                        color = if (isUser) Color(0xFF10B981) else Color(0xFFE5E7EB),
                        contentColor = if (isUser) Color.White else Color.Black
                    ) {
                        if (isUser) {
                            androidx.compose.ui.viewinterop.AndroidView(
                                factory = { ctx ->
                                    SafeSelectableTextView(ctx).apply {
                                        setTextColor(android.graphics.Color.WHITE)
                                        textSize = 14f
                                        setTextIsSelectable(true)
                                        setPadding(0, 0, 0, 0)
                                    }
                                },
                                update = { view ->
                                    view.text = msg.content
                                },
                                modifier = Modifier.padding(12.dp)
                            )
                        } else {
                            val contentWithCursor = msg.content + if (msg.isStreaming) " █" else ""
                            MarkwonRenderer(
                                markdown = contentWithCursor,
                                modifier = Modifier.padding(12.dp)
                            )
                        }
                    }
                }
            }
        }

        Row(
            modifier = Modifier
                .fillMaxWidth()
                .padding(8.dp)
                .navigationBarsPadding()
                .imePadding(),
            verticalAlignment = Alignment.CenterVertically
        ) {
            OutlinedTextField(
                value = inputText,
                onValueChange = { inputText = it },
                modifier = Modifier.weight(1f),
                placeholder = { Text("输入你想问的问题...") },
                shape = RoundedCornerShape(20.dp),
                enabled = !isAnyStreaming
            )
            Spacer(modifier = Modifier.width(8.dp))
            IconButton(
                onClick = {
                    if (isAnyStreaming) {
                        onCancelStreaming()
                    } else if (inputText.isNotBlank()) {
                        onSendMessage(inputText)
                        inputText = ""
                    }
                },
                modifier = Modifier.background(
                    if (isAnyStreaming) Color.Red else Color(0xFF10B981),
                    RoundedCornerShape(50)
                )
            ) {
                Icon(
                    if (isAnyStreaming) Icons.Default.Close else Icons.Default.Send,
                    contentDescription = if (isAnyStreaming) "停止" else "发送",
                    tint = Color.White
                )
            }
        }
    }
}

@Composable
fun MarkwonRenderer(markdown: String, modifier: Modifier) {
    androidx.compose.ui.viewinterop.AndroidView(
        factory = { ctx ->
            val textView = SafeSelectableTextView(ctx).apply {
                setTextColor(android.graphics.Color.parseColor("#1F2937"))
                textSize = 14f
                setTextIsSelectable(true) // 👈 启用选择复制功能
                movementMethod = android.text.method.LinkMovementMethod.getInstance()
                setLineSpacing(0f, 1.15f)
                setPadding(0, 0, 0, 0)
            }

            val markwon = io.noties.markwon.Markwon.builder(ctx)
                .usePlugin(io.noties.markwon.core.CorePlugin.create())
                .usePlugin(io.noties.markwon.ext.tables.TablePlugin.create(ctx))
                .usePlugin(io.noties.markwon.html.HtmlPlugin.create())
                .usePlugin(io.noties.markwon.linkify.LinkifyPlugin.create())
                .usePlugin(io.noties.markwon.ext.strikethrough.StrikethroughPlugin.create())
                .usePlugin(io.noties.markwon.ext.tasklist.TaskListPlugin.create(ctx))
                .build()

            textView.tag = markwon
            textView
        },
        update = { view ->
            try {
                val markwon = view.tag as? io.noties.markwon.Markwon
                if (markwon != null) {
                    markwon.setMarkdown(view, markdown)
                } else {
                    view.text = markdown
                }
            } catch (e: Exception) {
                view.text = markdown
            }
        },
        modifier = modifier
    )
}
