package com.example.notesai.presentation.screens.ai.components

import androidx.compose.animation.*
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.filled.*
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.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.example.notesai.data.model.ChatMessage
import com.example.notesai.util.MarkdownText
import com.example.notesai.util.MarkdownStripper
import com.example.notesai.util.AppColors
import com.example.notesai.util.Constants
import java.text.SimpleDateFormat
import java.util.*

@Composable
fun ChatBubble(
    message: ChatMessage,
    onCopy: (String) -> Unit, // CHANGED: Sekarang terima text parameter
    showCopied: Boolean
) {
    val dateFormat = remember { SimpleDateFormat("HH:mm", Locale("id", "ID")) }
    var showCopyMenu by remember { mutableStateOf(false) }

    Column(
        modifier = Modifier.fillMaxWidth(),
        horizontalAlignment = if (message.isUser) Alignment.End else Alignment.Start
    ) {
        if (message.isUser) {
            // User Message (tidak berubah)
            Surface(
                color = AppColors.Primary,
                shape = RoundedCornerShape(
                    topStart = Constants.Radius.Large.dp,
                    topEnd = Constants.Radius.Large.dp,
                    bottomStart = Constants.Radius.Large.dp,
                    bottomEnd = 4.dp
                ),
                shadowElevation = 2.dp,
                modifier = Modifier.widthIn(max = 320.dp)
            ) {
                Column(
                    modifier = Modifier.padding(12.dp)
                ) {
                    Row(
                        horizontalArrangement = Arrangement.spacedBy(8.dp),
                        verticalAlignment = Alignment.CenterVertically
                    ) {
                        Icon(
                            Icons.Default.Person,
                            contentDescription = null,
                            tint = Color.White.copy(alpha = 0.9f),
                            modifier = Modifier.size(16.dp)
                        )
                        Text(
                            "Anda",
                            color = Color.White.copy(alpha = 0.9f),
                            fontSize = 12.sp,
                            fontWeight = FontWeight.SemiBold
                        )
                    }

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

                    Text(
                        message.message,
                        color = Color.White,
                        style = MaterialTheme.typography.bodyMedium,
                        lineHeight = 20.sp
                    )

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

                    Text(
                        dateFormat.format(Date(message.timestamp)),
                        color = Color.White.copy(alpha = 0.7f),
                        fontSize = 11.sp
                    )
                }
            }
        } else {
            // AI Message with IMPROVED Copy Options
            Surface(
                color = AppColors.SurfaceVariant,
                shape = RoundedCornerShape(
                    topStart = Constants.Radius.Large.dp,
                    topEnd = Constants.Radius.Large.dp,
                    bottomStart = 4.dp,
                    bottomEnd = Constants.Radius.Large.dp
                ),
                shadowElevation = 2.dp,
                modifier = Modifier.widthIn(max = 320.dp)
            ) {
                Column(
                    modifier = Modifier.padding(12.dp)
                ) {
                    Row(
                        modifier = Modifier.fillMaxWidth(),
                        horizontalArrangement = Arrangement.SpaceBetween,
                        verticalAlignment = Alignment.CenterVertically
                    ) {
                        Row(
                            horizontalArrangement = Arrangement.spacedBy(8.dp),
                            verticalAlignment = Alignment.CenterVertically
                        ) {
                            Icon(
                                Icons.Default.SmartToy,
                                contentDescription = null,
                                tint = AppColors.Primary,
                                modifier = Modifier.size(16.dp)
                            )
                            Text(
                                "AI Assistant",
                                color = AppColors.OnSurfaceVariant,
                                fontSize = 12.sp,
                                fontWeight = FontWeight.SemiBold
                            )
                        }

                        // IMPROVED: Copy Button with Dropdown Menu
                        Box {
                            IconButton(
                                onClick = { showCopyMenu = !showCopyMenu },
                                modifier = Modifier.size(28.dp)
                            ) {
                                AnimatedContent(
                                    targetState = showCopied,
                                    transitionSpec = {
                                        fadeIn() + scaleIn() togetherWith fadeOut() + scaleOut()
                                    },
                                    label = "copy_icon"
                                ) { copied ->
                                    Icon(
                                        if (copied) Icons.Default.Check else Icons.Default.ContentCopy,
                                        contentDescription = if (copied) "Copied" else "Copy",
                                        tint = if (copied) AppColors.Success else AppColors.OnSurfaceVariant,
                                        modifier = Modifier.size(16.dp)
                                    )
                                }
                            }

                            // Dropdown Menu untuk pilihan copy
                            DropdownMenu(
                                expanded = showCopyMenu,
                                onDismissRequest = { showCopyMenu = false },
                                modifier = Modifier.background(AppColors.SurfaceElevated)
                            ) {
                                // Option 1: Copy dengan Format (Markdown)
                                DropdownMenuItem(
                                    text = {
                                        Row(
                                            horizontalArrangement = Arrangement.spacedBy(10.dp),
                                            verticalAlignment = Alignment.CenterVertically
                                        ) {
                                            Icon(
                                                Icons.Default.Code,
                                                contentDescription = null,
                                                tint = AppColors.Primary,
                                                modifier = Modifier.size(18.dp)
                                            )
                                            Column {
                                                Text(
                                                    "Copy dengan Format",
                                                    fontSize = 13.sp,
                                                    color = AppColors.OnSurface,
                                                    fontWeight = FontWeight.Medium
                                                )
                                                Text(
                                                    "Termasuk markdown",
                                                    fontSize = 10.sp,
                                                    color = AppColors.OnSurfaceTertiary
                                                )
                                            }
                                        }
                                    },
                                    onClick = {
                                        onCopy(message.message) // Copy original dengan markdown
                                        showCopyMenu = false
                                    }
                                )

                                HorizontalDivider(color = AppColors.Divider)

                                // Option 2: Copy Teks Asli (Plain Text)
                                DropdownMenuItem(
                                    text = {
                                        Row(
                                            horizontalArrangement = Arrangement.spacedBy(10.dp),
                                            verticalAlignment = Alignment.CenterVertically
                                        ) {
                                            Icon(
                                                Icons.Default.TextFields,
                                                contentDescription = null,
                                                tint = AppColors.Secondary,
                                                modifier = Modifier.size(18.dp)
                                            )
                                            Column {
                                                Text(
                                                    "Copy Teks Asli",
                                                    fontSize = 13.sp,
                                                    color = AppColors.OnSurface,
                                                    fontWeight = FontWeight.Medium
                                                )
                                                Text(
                                                    "Tanpa format",
                                                    fontSize = 10.sp,
                                                    color = AppColors.OnSurfaceTertiary
                                                )
                                            }
                                        }
                                    },
                                    onClick = {
                                        val plainText = MarkdownStripper.stripMarkdown(message.message)
                                        onCopy(plainText) // Copy plain text tanpa markdown
                                        showCopyMenu = false
                                    }
                                )
                            }
                        }
                    }

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

                    // Use MarkdownText for AI responses
                    MarkdownText(
                        markdown = message.message,
                        modifier = Modifier.fillMaxWidth()
                    )

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

                    Text(
                        dateFormat.format(Date(message.timestamp)),
                        color = AppColors.OnSurfaceTertiary,
                        fontSize = 11.sp
                    )
                }
            }
        }
    }
}