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

import androidx.compose.animation.*
import androidx.compose.animation.core.*
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.interaction.MutableInteractionSource
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.shape.CircleShape
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.AnnotatedString
import androidx.compose.ui.text.SpanStyle
import androidx.compose.ui.text.buildAnnotatedString
import androidx.compose.ui.text.font.FontFamily
import androidx.compose.ui.text.font.FontStyle
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextDecoration
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.text.withStyle
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import com.example.notesai.data.model.ChatHistory
import com.example.notesai.data.model.Category
import com.example.notesai.data.model.Note
import com.example.notesai.util.AppColors
import com.example.notesai.util.Constants
import java.text.SimpleDateFormat
import java.util.*

@Composable
fun ChatHistoryDrawer(
    chatHistories: List<ChatHistory>,
    categories: List<Category>,
    notes: List<Note>,
    selectedCategory: Category?,
    onDismiss: () -> Unit,
    onHistoryClick: (ChatHistory) -> Unit,
    onDeleteHistory: (String) -> Unit,
    onCategorySelected: (Category?) -> Unit,
    onNewChat: () -> Unit,
    onEditHistoryTitle: (String, String) -> Unit = { _, _ -> }
) {
    var showCategoryDropdown by remember { mutableStateOf(false) }
    var searchQuery by remember { mutableStateOf("") }

    // Filter categories with notes
    val categoriesWithNotes = categories.filter { category ->
        notes.any { note -> note.categoryId == category.id && !note.isArchived && !note.isDeleted }
    }

    // Filter and search histories
    val filteredHistories = chatHistories
        .filter { !it.isDeleted }
        .filter { history ->
            if (searchQuery.isBlank()) true
            else history.lastMessagePreview.contains(searchQuery, ignoreCase = true) ||
                    history.categoryName.contains(searchQuery, ignoreCase = true)
        }

    // Group by date
    val groupedHistories = groupHistoriesByDate(filteredHistories)

    Box(
        modifier = Modifier
            .fillMaxSize()
            .background(Color.Black.copy(alpha = 0.5f))
            .clickable(
                onClick = onDismiss,
                indication = null,
                interactionSource = remember { MutableInteractionSource() }
            )
    ) {
        Surface(
            modifier = Modifier
                .fillMaxHeight()
                .width(320.dp)
                .align(Alignment.CenterStart)
                .clickable(
                    onClick = {},
                    indication = null,
                    interactionSource = remember { MutableInteractionSource() }
                ),
            color = AppColors.Surface,
            shadowElevation = Constants.Elevation.ExtraLarge.dp
        ) {
            Column(modifier = Modifier.fillMaxSize()) {
                // Compact Header
                Surface(
                    color = AppColors.Primary.copy(alpha = 0.05f),
                    modifier = Modifier.fillMaxWidth()
                ) {
                    Column(modifier = Modifier.padding(16.dp)) {
                        // Top Row
                        Row(
                            modifier = Modifier.fillMaxWidth(),
                            horizontalArrangement = Arrangement.SpaceBetween,
                            verticalAlignment = Alignment.CenterVertically
                        ) {
                            Row(
                                verticalAlignment = Alignment.CenterVertically,
                                horizontalArrangement = Arrangement.spacedBy(10.dp)
                            ) {
                                Icon(
                                    Icons.Default.History,
                                    contentDescription = null,
                                    tint = AppColors.Primary,
                                    modifier = Modifier.size(24.dp)
                                )
                                Column {
                                    Text(
                                        "Riwayat Chat",
                                        style = MaterialTheme.typography.titleMedium,
                                        color = AppColors.OnBackground,
                                        fontWeight = FontWeight.Bold,
                                        fontSize = 18.sp
                                    )
                                    Text(
                                        "${filteredHistories.size} percakapan",
                                        style = MaterialTheme.typography.bodySmall,
                                        color = AppColors.OnSurfaceVariant,
                                        fontSize = 11.sp
                                    )
                                }
                            }

                            IconButton(
                                onClick = onDismiss,
                                modifier = Modifier.size(32.dp)
                            ) {
                                Icon(
                                    Icons.Default.Close,
                                    contentDescription = "Close",
                                    tint = AppColors.OnSurfaceVariant,
                                    modifier = Modifier.size(20.dp)
                                )
                            }
                        }

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

                        // Compact Search
                        OutlinedTextField(
                            value = searchQuery,
                            onValueChange = { searchQuery = it },
                            modifier = Modifier.fillMaxWidth(),
                            placeholder = {
                                Text(
                                    "Cari riwayat...",
                                    color = AppColors.OnSurfaceTertiary,
                                    fontSize = 13.sp
                                )
                            },
                            leadingIcon = {
                                Icon(
                                    Icons.Default.Search,
                                    contentDescription = null,
                                    tint = AppColors.OnSurfaceVariant,
                                    modifier = Modifier.size(18.dp)
                                )
                            },
                            trailingIcon = {
                                if (searchQuery.isNotEmpty()) {
                                    IconButton(
                                        onClick = { searchQuery = "" },
                                        modifier = Modifier.size(32.dp)
                                    ) {
                                        Icon(
                                            Icons.Default.Clear,
                                            contentDescription = "Clear",
                                            tint = AppColors.OnSurfaceVariant,
                                            modifier = Modifier.size(16.dp)
                                        )
                                    }
                                }
                            },
                            colors = OutlinedTextFieldDefaults.colors(
                                focusedContainerColor = AppColors.SurfaceVariant,
                                unfocusedContainerColor = AppColors.SurfaceVariant,
                                focusedBorderColor = AppColors.Primary,
                                unfocusedBorderColor = Color.Transparent,
                                cursorColor = AppColors.Primary,
                                focusedTextColor = AppColors.OnSurface,
                                unfocusedTextColor = AppColors.OnSurface
                            ),
                            shape = RoundedCornerShape(10.dp),
                            singleLine = true,
                            textStyle = MaterialTheme.typography.bodyMedium.copy(fontSize = 13.sp)
                        )
                    }
                }

                // Compact Category Filter
                Column(
                    modifier = Modifier
                        .fillMaxWidth()
                        .padding(horizontal = 16.dp, vertical = 10.dp)
                ) {
                    Text(
                        "Kategori",
                        style = MaterialTheme.typography.labelSmall,
                        color = AppColors.OnSurfaceTertiary,
                        fontSize = 10.sp,
                        fontWeight = FontWeight.SemiBold
                    )

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

                    Box {
                        Card(
                            onClick = { showCategoryDropdown = !showCategoryDropdown },
                            modifier = Modifier.fillMaxWidth(),
                            colors = CardDefaults.cardColors(
                                containerColor = AppColors.SurfaceVariant
                            ),
                            shape = RoundedCornerShape(8.dp)
                        ) {
                            Row(
                                modifier = Modifier
                                    .fillMaxWidth()
                                    .padding(horizontal = 12.dp, vertical = 10.dp),
                                horizontalArrangement = Arrangement.SpaceBetween,
                                verticalAlignment = Alignment.CenterVertically
                            ) {
                                Row(
                                    modifier = Modifier.weight(1f),
                                    verticalAlignment = Alignment.CenterVertically,
                                    horizontalArrangement = Arrangement.spacedBy(6.dp)
                                ) {
                                    Icon(
                                        Icons.Default.Folder,
                                        contentDescription = null,
                                        tint = selectedCategory?.let { Color(it.gradientStart) }
                                            ?: AppColors.Primary,
                                        modifier = Modifier.size(16.dp)
                                    )
                                    Text(
                                        selectedCategory?.name ?: "Semua",
                                        color = AppColors.OnSurface,
                                        fontSize = 13.sp,
                                        fontWeight = FontWeight.Medium,
                                        maxLines = 1,
                                        overflow = TextOverflow.Ellipsis
                                    )
                                }
                                Icon(
                                    if (showCategoryDropdown) Icons.Default.ArrowDropUp
                                    else Icons.Default.ArrowDropDown,
                                    contentDescription = null,
                                    tint = AppColors.OnSurfaceVariant,
                                    modifier = Modifier.size(20.dp)
                                )
                            }
                        }

                        DropdownMenu(
                            expanded = showCategoryDropdown,
                            onDismissRequest = { showCategoryDropdown = false },
                            modifier = Modifier
                                .width(280.dp)
                                .background(AppColors.SurfaceElevated)
                        ) {
                            DropdownMenuItem(
                                text = {
                                    Row(
                                        verticalAlignment = Alignment.CenterVertically,
                                        horizontalArrangement = Arrangement.spacedBy(8.dp)
                                    ) {
                                        Icon(
                                            Icons.Default.Folder,
                                            contentDescription = null,
                                            tint = AppColors.OnSurfaceVariant,
                                            modifier = Modifier.size(16.dp)
                                        )
                                        Text(
                                            "Semua Kategori",
                                            color = AppColors.OnSurface,
                                            fontSize = 13.sp
                                        )
                                    }
                                },
                                onClick = {
                                    onCategorySelected(null)
                                    showCategoryDropdown = false
                                    onNewChat()
                                },
                                leadingIcon = {
                                    if (selectedCategory == null) {
                                        Icon(
                                            Icons.Default.Check,
                                            contentDescription = null,
                                            tint = AppColors.Primary,
                                            modifier = Modifier.size(18.dp)
                                        )
                                    }
                                }
                            )

                            if (categoriesWithNotes.isNotEmpty()) {
                                HorizontalDivider(color = AppColors.Divider)
                            }

                            categoriesWithNotes.forEach { category ->
                                val notesCount = notes.count {
                                    it.categoryId == category.id && !it.isArchived && !it.isDeleted
                                }

                                DropdownMenuItem(
                                    text = {
                                        Row(
                                            modifier = Modifier.fillMaxWidth(),
                                            horizontalArrangement = Arrangement.SpaceBetween,
                                            verticalAlignment = Alignment.CenterVertically
                                        ) {
                                            Row(
                                                verticalAlignment = Alignment.CenterVertically,
                                                horizontalArrangement = Arrangement.spacedBy(8.dp)
                                            ) {
                                                Icon(
                                                    Icons.Default.Folder,
                                                    contentDescription = null,
                                                    tint = Color(category.gradientStart),
                                                    modifier = Modifier.size(16.dp)
                                                )
                                                Text(
                                                    category.name,
                                                    color = AppColors.OnSurface,
                                                    fontSize = 13.sp
                                                )
                                            }

                                            Surface(
                                                color = AppColors.Primary.copy(alpha = 0.15f),
                                                shape = RoundedCornerShape(4.dp)
                                            ) {
                                                Text(
                                                    notesCount.toString(),
                                                    modifier = Modifier.padding(
                                                        horizontal = 6.dp,
                                                        vertical = 2.dp
                                                    ),
                                                    color = AppColors.Primary,
                                                    fontSize = 10.sp,
                                                    fontWeight = FontWeight.Bold
                                                )
                                            }
                                        }
                                    },
                                    onClick = {
                                        onCategorySelected(category)
                                        showCategoryDropdown = false
                                        onNewChat()
                                    },
                                    leadingIcon = {
                                        if (selectedCategory?.id == category.id) {
                                            Icon(
                                                Icons.Default.Check,
                                                contentDescription = null,
                                                tint = AppColors.Primary,
                                                modifier = Modifier.size(18.dp)
                                            )
                                        }
                                    }
                                )
                            }
                        }
                    }
                }

                HorizontalDivider(color = AppColors.Divider)

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

                // Compact History List
                if (filteredHistories.isEmpty()) {
                    EmptyHistoryState(
                        searchQuery = searchQuery,
                        onClearSearch = { searchQuery = "" }
                    )
                } else {
                    LazyColumn(
                        modifier = Modifier
                            .fillMaxWidth()
                            .weight(1f),
                        contentPadding = PaddingValues(8.dp),
                        verticalArrangement = Arrangement.spacedBy(4.dp)
                    ) {
                        groupedHistories.forEach { (dateGroup, histories) ->
                            item {
                                DateGroupHeader(dateGroup)
                            }

                            items(
                                items = histories,
                                key = { it.id }
                            ) { history ->
                                CompactChatHistoryItem(
                                    history = history,
                                    onClick = { onHistoryClick(history) },
                                    onDelete = { onDeleteHistory(history.id) },
                                    onEdit = { newTitle ->
                                        onEditHistoryTitle(history.id, newTitle)
                                    }
                                )
                            }
                        }
                    }
                }
            }
        }
    }
}

@Composable
private fun DateGroupHeader(dateGroup: String) {
    Row(
        modifier = Modifier
            .fillMaxWidth()
            .padding(horizontal = 8.dp, vertical = 6.dp),
        verticalAlignment = Alignment.CenterVertically,
        horizontalArrangement = Arrangement.spacedBy(6.dp)
    ) {
        Text(
            dateGroup,
            style = MaterialTheme.typography.labelSmall,
            color = AppColors.OnSurfaceVariant,
            fontWeight = FontWeight.Bold,
            fontSize = 11.sp
        )
        HorizontalDivider(
            modifier = Modifier.weight(1f),
            color = AppColors.Divider.copy(alpha = 0.5f)
        )
    }
}

@Composable
private fun CompactChatHistoryItem(
    history: ChatHistory,
    onClick: () -> Unit,
    onDelete: () -> Unit,
    onEdit: (String) -> Unit
) {
    var showMenu by remember { mutableStateOf(false) }
    var showDeleteConfirm by remember { mutableStateOf(false) }
    var showEditDialog by remember { mutableStateOf(false) }
    val dateFormat = remember { SimpleDateFormat("HH:mm", Locale("id", "ID")) }

    Box(modifier = Modifier.fillMaxWidth()) {
        Card(
            onClick = onClick,
            modifier = Modifier.fillMaxWidth(),
            colors = CardDefaults.cardColors(
                containerColor = AppColors.SurfaceVariant
            ),
            shape = RoundedCornerShape(8.dp)
        ) {
            Row(
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(10.dp),
                horizontalArrangement = Arrangement.SpaceBetween,
                verticalAlignment = Alignment.CenterVertically
            ) {
                // Left Content
                Row(
                    modifier = Modifier.weight(1f),
                    horizontalArrangement = Arrangement.spacedBy(8.dp),
                    verticalAlignment = Alignment.CenterVertically
                ) {
                    // Chat Icon
                    Box(
                        modifier = Modifier
                            .size(32.dp)
                            .background(
                                AppColors.Primary.copy(alpha = 0.15f),
                                CircleShape
                            ),
                        contentAlignment = Alignment.Center
                    ) {
                        Icon(
                            Icons.Default.Chat,
                            contentDescription = null,
                            tint = AppColors.Primary,
                            modifier = Modifier.size(16.dp)
                        )
                    }

                    // Text Content
                    Column(
                        modifier = Modifier.weight(1f),
                        verticalArrangement = Arrangement.spacedBy(3.dp)
                    ) {
                        // Preview Text with Markdown (use customTitle if available)
                        Text(
                            text = buildAnnotatedString {
                                appendInlineMarkdown(history.customTitle ?: history.lastMessagePreview)
                            },
                            style = MaterialTheme.typography.bodySmall,
                            color = AppColors.OnSurface,
                            maxLines = 1,
                            overflow = TextOverflow.Ellipsis,
                            fontSize = 13.sp,
                            fontWeight = FontWeight.Medium
                        )

                        // Bottom Info Row
                        Row(
                            horizontalArrangement = Arrangement.spacedBy(6.dp),
                            verticalAlignment = Alignment.CenterVertically
                        ) {
                            // Category Badge
                            Surface(
                                color = AppColors.Primary.copy(alpha = 0.1f),
                                shape = RoundedCornerShape(4.dp)
                            ) {
                                Row(
                                    modifier = Modifier.padding(horizontal = 4.dp, vertical = 2.dp),
                                    horizontalArrangement = Arrangement.spacedBy(3.dp),
                                    verticalAlignment = Alignment.CenterVertically
                                ) {
                                    Icon(
                                        Icons.Default.Folder,
                                        contentDescription = null,
                                        tint = AppColors.Primary,
                                        modifier = Modifier.size(9.dp)
                                    )
                                    Text(
                                        history.categoryName,
                                        color = AppColors.Primary,
                                        fontSize = 9.sp,
                                        fontWeight = FontWeight.SemiBold
                                    )
                                }
                            }

                            // Separator Dot
                            Text(
                                "•",
                                color = AppColors.OnSurfaceTertiary,
                                fontSize = 9.sp
                            )

                            // Message Count
                            Row(
                                horizontalArrangement = Arrangement.spacedBy(2.dp),
                                verticalAlignment = Alignment.CenterVertically
                            ) {
                                Icon(
                                    Icons.Default.ChatBubbleOutline,
                                    contentDescription = null,
                                    tint = AppColors.OnSurfaceTertiary,
                                    modifier = Modifier.size(9.dp)
                                )
                                Text(
                                    "${history.messages.size}",
                                    color = AppColors.OnSurfaceTertiary,
                                    fontSize = 10.sp
                                )
                            }

                            // Separator Dot
                            Text(
                                "•",
                                color = AppColors.OnSurfaceTertiary,
                                fontSize = 9.sp
                            )

                            // Time
                            Text(
                                dateFormat.format(Date(history.timestamp)),
                                color = AppColors.OnSurfaceTertiary,
                                fontSize = 10.sp
                            )
                        }
                    }
                }

                // Menu Button
                IconButton(
                    onClick = { showMenu = true },
                    modifier = Modifier.size(28.dp)
                ) {
                    Icon(
                        Icons.Default.MoreVert,
                        contentDescription = "Menu",
                        tint = AppColors.OnSurfaceVariant,
                        modifier = Modifier.size(18.dp)
                    )
                }
            }
        }

        // Dropdown Menu
        DropdownMenu(
            expanded = showMenu,
            onDismissRequest = { showMenu = false },
            modifier = Modifier.background(AppColors.SurfaceElevated)
        ) {
            DropdownMenuItem(
                text = {
                    Row(
                        horizontalArrangement = Arrangement.spacedBy(10.dp),
                        verticalAlignment = Alignment.CenterVertically
                    ) {
                        Icon(
                            Icons.Default.Edit,
                            contentDescription = null,
                            tint = AppColors.Primary,
                            modifier = Modifier.size(18.dp)
                        )
                        Text(
                            "Edit Judul",
                            fontSize = 13.sp,
                            color = AppColors.OnSurface
                        )
                    }
                },
                onClick = {
                    showMenu = false
                    showEditDialog = true
                }
            )

            HorizontalDivider(color = AppColors.Divider)

            DropdownMenuItem(
                text = {
                    Row(
                        horizontalArrangement = Arrangement.spacedBy(10.dp),
                        verticalAlignment = Alignment.CenterVertically
                    ) {
                        Icon(
                            Icons.Default.Delete,
                            contentDescription = null,
                            tint = AppColors.Error,
                            modifier = Modifier.size(18.dp)
                        )
                        Text(
                            "Hapus",
                            fontSize = 13.sp,
                            color = AppColors.Error
                        )
                    }
                },
                onClick = {
                    showMenu = false
                    showDeleteConfirm = true
                }
            )
        }
    }

    // Delete Dialog
    if (showDeleteConfirm) {
        AlertDialog(
            onDismissRequest = { showDeleteConfirm = false },
            icon = {
                Icon(
                    Icons.Default.DeleteForever,
                    contentDescription = null,
                    tint = AppColors.Error
                )
            },
            title = {
                Text(
                    "Hapus Riwayat?",
                    fontWeight = FontWeight.Bold,
                    fontSize = 18.sp
                )
            },
            text = {
                Text(
                    "Riwayat chat ini akan dihapus permanen dan tidak dapat dikembalikan.",
                    fontSize = 14.sp
                )
            },
            confirmButton = {
                Button(
                    onClick = {
                        onDelete()
                        showDeleteConfirm = false
                    },
                    colors = ButtonDefaults.buttonColors(
                        containerColor = AppColors.Error
                    ),
                    shape = RoundedCornerShape(8.dp)
                ) {
                    Text("Hapus", fontSize = 13.sp)
                }
            },
            dismissButton = {
                TextButton(onClick = { showDeleteConfirm = false }) {
                    Text("Batal", fontSize = 13.sp)
                }
            },
            containerColor = AppColors.SurfaceElevated,
            shape = RoundedCornerShape(16.dp)
        )
    }

    // Edit Dialog
    if (showEditDialog) {
        val maxTitleLength = 30
        var editTitle by remember {
            val currentTitle = history.customTitle ?: history.lastMessagePreview
            mutableStateOf(currentTitle.take(maxTitleLength))
        }

        AlertDialog(
            onDismissRequest = { showEditDialog = false },
            icon = {
                Icon(
                    Icons.Default.Edit,
                    contentDescription = null,
                    tint = AppColors.Primary
                )
            },
            title = {
                Text(
                    "Edit Judul Chat",
                    fontWeight = FontWeight.Bold,
                    fontSize = 18.sp
                )
            },
            text = {
                Column {
                    Text(
                        "Maks 30 karakter • Gunakan markdown",
                        fontSize = 11.sp,
                        color = AppColors.OnSurfaceVariant
                    )
                    Spacer(modifier = Modifier.height(12.dp))
                    OutlinedTextField(
                        value = editTitle,
                        onValueChange = {
                            if (it.length <= maxTitleLength) {
                                editTitle = it
                            }
                        },
                        label = {
                            Text(
                                "Judul Chat",
                                fontSize = 12.sp
                            )
                        },
                        placeholder = {
                            Text(
                                "**Analisis** Data",
                                fontSize = 11.sp
                            )
                        },
                        supportingText = {
                            Row(
                                modifier = Modifier.fillMaxWidth(),
                                horizontalArrangement = Arrangement.End
                            ) {
                                Text(
                                    "${editTitle.length}/$maxTitleLength",
                                    fontSize = 10.sp,
                                    color = when {
                                        editTitle.length >= maxTitleLength -> AppColors.Error
                                        editTitle.length >= maxTitleLength - 5 -> AppColors.Primary
                                        else -> AppColors.OnSurfaceTertiary
                                    },
                                    fontWeight = if (editTitle.length >= maxTitleLength - 5)
                                        FontWeight.Bold
                                    else
                                        FontWeight.Normal
                                )
                            }
                        },
                        singleLine = true,
                        colors = OutlinedTextFieldDefaults.colors(
                            focusedBorderColor = if (editTitle.length >= maxTitleLength)
                                AppColors.Error
                            else
                                AppColors.Primary,
                            unfocusedBorderColor = if (editTitle.length >= maxTitleLength)
                                AppColors.Error.copy(alpha = 0.5f)
                            else
                                Color.Gray,
                            cursorColor = AppColors.Primary
                        ),
                        shape = RoundedCornerShape(8.dp),
                        textStyle = MaterialTheme.typography.bodyMedium.copy(fontSize = 13.sp)
                    )

                    // Preview
                    if (editTitle.isNotBlank()) {
                        Spacer(modifier = Modifier.height(8.dp))
                        Text(
                            "Preview:",
                            fontSize = 10.sp,
                            color = AppColors.OnSurfaceTertiary,
                            fontWeight = FontWeight.SemiBold
                        )
                        Spacer(modifier = Modifier.height(4.dp))
                        Surface(
                            color = AppColors.SurfaceVariant,
                            shape = RoundedCornerShape(6.dp)
                        ) {
                            Text(
                                text = buildAnnotatedString {
                                    appendInlineMarkdown(editTitle)
                                },
                                modifier = Modifier.padding(8.dp),
                                fontSize = 12.sp,
                                maxLines = 1,
                                overflow = TextOverflow.Ellipsis
                            )
                        }
                    }
                }
            },
            confirmButton = {
                Button(
                    onClick = {
                        if (editTitle.isNotBlank()) {
                            onEdit(editTitle.trim())
                            showEditDialog = false
                        }
                    },
                    enabled = editTitle.isNotBlank() && editTitle.trim().isNotEmpty(),
                    colors = ButtonDefaults.buttonColors(
                        containerColor = AppColors.Primary,
                        disabledContainerColor = AppColors.OnSurfaceVariant.copy(alpha = 0.3f)
                    ),
                    shape = RoundedCornerShape(8.dp)
                ) {
                    Text("Simpan", fontSize = 13.sp)
                }
            },
            dismissButton = {
                TextButton(onClick = { showEditDialog = false }) {
                    Text("Batal", fontSize = 13.sp)
                }
            },
            containerColor = AppColors.SurfaceElevated,
            shape = RoundedCornerShape(16.dp)
        )
    }
}

@Composable
private fun EmptyHistoryState(
    searchQuery: String,
    onClearSearch: () -> Unit
) {
    Column(
        modifier = Modifier
            .fillMaxSize()
            .padding(24.dp),
        horizontalAlignment = Alignment.CenterHorizontally,
        verticalArrangement = Arrangement.Center
    ) {
        Icon(
            if (searchQuery.isNotEmpty()) Icons.Default.SearchOff
            else Icons.Default.ChatBubbleOutline,
            contentDescription = null,
            modifier = Modifier.size(56.dp),
            tint = AppColors.OnSurfaceVariant.copy(alpha = 0.4f)
        )

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

        Text(
            if (searchQuery.isNotEmpty()) "Tidak ditemukan"
            else "Belum ada riwayat",
            style = MaterialTheme.typography.titleMedium,
            color = AppColors.OnSurfaceVariant,
            fontWeight = FontWeight.SemiBold,
            fontSize = 16.sp
        )

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

        Text(
            if (searchQuery.isNotEmpty())
                "Coba kata kunci lain"
            else
                "Mulai chat dengan AI",
            style = MaterialTheme.typography.bodySmall,
            color = AppColors.OnSurfaceTertiary,
            fontSize = 16.sp
        )

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

        Text(
            if (searchQuery.isNotEmpty())
                "Coba kata kunci lain"
            else
                "Mulai chat dengan AI",
            style = MaterialTheme.typography.bodySmall,
            color = AppColors.OnSurfaceTertiary,
            fontSize = 12.sp
        )

        if (searchQuery.isNotEmpty()) {
            Spacer(modifier = Modifier.height(16.dp))

            Button(
                onClick = onClearSearch,
                colors = ButtonDefaults.buttonColors(
                    containerColor = AppColors.Primary
                ),
                shape = RoundedCornerShape(8.dp),
                contentPadding = PaddingValues(horizontal = 16.dp, vertical = 8.dp)
            ) {
                Icon(
                    Icons.Default.Clear,
                    contentDescription = null,
                    modifier = Modifier.size(14.dp)
                )
                Spacer(modifier = Modifier.width(6.dp))
                Text("Hapus Pencarian", fontSize = 12.sp)
            }
        }
    }
}

// Helper function
private fun groupHistoriesByDate(histories: List<ChatHistory>): Map<String, List<ChatHistory>> {
    val calendar = Calendar.getInstance()
    val today = calendar.apply {
        set(Calendar.HOUR_OF_DAY, 0)
        set(Calendar.MINUTE, 0)
        set(Calendar.SECOND, 0)
        set(Calendar.MILLISECOND, 0)
    }.timeInMillis

    val yesterday = calendar.apply {
        add(Calendar.DAY_OF_YEAR, -1)
    }.timeInMillis

    val weekAgo = calendar.apply {
        set(Calendar.HOUR_OF_DAY, 0)
        set(Calendar.MINUTE, 0)
        set(Calendar.SECOND, 0)
        set(Calendar.MILLISECOND, 0)
        add(Calendar.DAY_OF_YEAR, -6)
    }.timeInMillis

    return histories
        .sortedByDescending { it.timestamp }
        .groupBy { history ->
            when {
                history.timestamp >= today -> "Hari Ini"
                history.timestamp >= yesterday -> "Kemarin"
                history.timestamp >= weekAgo -> "Minggu Ini"
                else -> "Lebih Lama"
            }
        }
}

// Parse inline markdown for chat history titles
private fun AnnotatedString.Builder.appendInlineMarkdown(text: String) {
    var currentIndex = 0
    var processedText = text

    // List of patterns to process
    val patterns = listOf(
        // Bold with **
        Regex("""\*\*(.+?)\*\*""") to { content: String ->
            withStyle(SpanStyle(fontWeight = FontWeight.Bold)) {
                append(content)
            }
        },
        // Inline code with `
        Regex("""`(.+?)`""") to { content: String ->
            withStyle(
                SpanStyle(
                    fontFamily = FontFamily.Monospace,
                    background = AppColors.Primary.copy(alpha = 0.15f)
                )
            ) {
                append(content)
            }
        },
        // Italic with * (but not **)
        Regex("""\*([^*]+?)\*""") to { content: String ->
            withStyle(SpanStyle(fontStyle = FontStyle.Italic)) {
                append(content)
            }
        },
        // Strikethrough with ~~
        Regex("""~~(.+?)~~""") to { content: String ->
            withStyle(SpanStyle(textDecoration = TextDecoration.LineThrough)) {
                append(content)
            }
        }
    )

    // Collect all matches
    data class Match(val start: Int, val end: Int, val content: String, val applier: (String) -> Unit)
    val matches = mutableListOf<Match>()

    patterns.forEach { (regex, applier) ->
        regex.findAll(processedText).forEach { matchResult ->
            val content = matchResult.groupValues[1]
            matches.add(
                Match(
                    start = matchResult.range.first,
                    end = matchResult.range.last + 1,
                    content = content,
                    applier = applier
                )
            )
        }
    }

    // Sort matches by start position and remove overlaps
    val sortedMatches = matches
        .sortedBy { it.start }
        .fold(mutableListOf<Match>()) { acc, match ->
            if (acc.isEmpty() || match.start >= acc.last().end) {
                acc.add(match)
            }
            acc
        }

    // Build the annotated string
    var lastIndex = 0
    sortedMatches.forEach { match ->
        // Append text before match
        if (match.start > lastIndex) {
            append(processedText.substring(lastIndex, match.start))
        }
        // Apply style
        match.applier(match.content)
        lastIndex = match.end
    }

    // Append remaining text
    if (lastIndex < processedText.length) {
        append(processedText.substring(lastIndex))
    }
}