// File: presentation/screens/main/components/CategoryCard.kt
package com.example.notesai.presentation.screens.main.components

import androidx.compose.animation.*
import androidx.compose.animation.core.*
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
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.material.icons.outlined.FolderOpen
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.draw.scale
import androidx.compose.ui.graphics.Brush
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.Category
import com.example.notesai.util.AppColors
import com.example.notesai.util.Constants

@Composable
fun CategoryCard(
    category: Category,
    noteCount: Int,
    onClick: () -> Unit,
    onDelete: () -> Unit = {},
    onEdit: (String, Long, Long) -> Unit = { _, _, _ -> },
    onPin: () -> Unit = {}
) {
    var showDeleteConfirm by remember { mutableStateOf(false) }
    var showEditDialog by remember { mutableStateOf(false) }
    var showMenu by remember { mutableStateOf(false) }
    var isPressed by remember { mutableStateOf(false) }

    // Smooth scale animation
    val scale by animateFloatAsState(
        targetValue = if (isPressed) 0.95f else 1f,
        animationSpec = spring(
            dampingRatio = Spring.DampingRatioMediumBouncy,
            stiffness = Spring.StiffnessLow
        ),
        label = "scale"
    )

    // Delete Confirmation Dialog
    if (showDeleteConfirm) {
        AlertDialog(
            onDismissRequest = { showDeleteConfirm = false },
            title = {
                Text(
                    "Pindahkan ke Sampah?",
                    color = AppColors.OnBackground,
                    fontWeight = FontWeight.Bold
                )
            },
            text = {
                Text(
                    "Kategori '${category.name}' dan $noteCount catatan di dalamnya akan dipindahkan ke sampah.",
                    color = AppColors.OnSurfaceVariant
                )
            },
            confirmButton = {
                Button(
                    onClick = {
                        onDelete()
                        showDeleteConfirm = false
                    },
                    colors = ButtonDefaults.buttonColors(
                        containerColor = AppColors.Error
                    )
                ) {
                    Text("Hapus", color = Color.White)
                }
            },
            dismissButton = {
                TextButton(onClick = { showDeleteConfirm = false }) {
                    Text("Batal", color = AppColors.OnSurfaceVariant)
                }
            },
            containerColor = AppColors.Surface,
            shape = RoundedCornerShape(Constants.Radius.Large.dp)
        )
    }

    // Edit Dialog
    if (showEditDialog) {
        EditCategoryDialog(
            category = category,
            onDismiss = { showEditDialog = false },
            onSave = { name, gradientStart, gradientEnd ->
                onEdit(name, gradientStart, gradientEnd)
                showEditDialog = false
            }
        )
    }

    // Main Card - Minimalist Design
    Card(
        modifier = Modifier
            .fillMaxWidth()
            .scale(scale)
            .clickable(onClick = onClick),
        shape = RoundedCornerShape(Constants.Radius.Large.dp),
        colors = CardDefaults.cardColors(
            containerColor = AppColors.Surface
        ),
        elevation = CardDefaults.cardElevation(
            defaultElevation = Constants.Elevation.Small.dp
        )
    ) {
        Box(
            modifier = Modifier
                .fillMaxWidth()
                .background(
                    brush = Brush.linearGradient(
                        colors = listOf(
                            Color(category.gradientStart).copy(alpha = 0.1f),
                            Color(category.gradientEnd).copy(alpha = 0.05f)
                        )
                    )
                )
        ) {
            Column(
                modifier = Modifier
                    .fillMaxWidth()
                    .padding(Constants.Spacing.Large.dp)
            ) {
                Row(
                    modifier = Modifier.fillMaxWidth(),
                    horizontalArrangement = Arrangement.SpaceBetween,
                    verticalAlignment = Alignment.Top
                ) {
                    // Icon dengan gradient accent
                    Box(
                        modifier = Modifier
                            .size(48.dp)
                            .clip(RoundedCornerShape(Constants.Radius.Medium.dp))
                            .background(
                                brush = Brush.linearGradient(
                                    colors = listOf(
                                        Color(category.gradientStart).copy(alpha = 0.2f),
                                        Color(category.gradientEnd).copy(alpha = 0.1f)
                                    )
                                )
                            ),
                        contentAlignment = Alignment.Center
                    ) {
                        Icon(
                            Icons.Outlined.FolderOpen,
                            contentDescription = null,
                            tint = Color(category.gradientStart),
                            modifier = Modifier.size(24.dp)
                        )
                    }

                    // Pin Indicator & Menu Button
                    Row(
                        horizontalArrangement = Arrangement.spacedBy(4.dp),
                        verticalAlignment = Alignment.CenterVertically
                    ) {
                        // Pin indicator (only show if pinned)
                        AnimatedVisibility(
                            visible = category.isPinned,
                            enter = scaleIn() + fadeIn(),
                            exit = scaleOut() + fadeOut()
                        ) {
                            Icon(
                                Icons.Default.PushPin,
                                contentDescription = "Pinned",
                                tint = AppColors.Warning,
                                modifier = Modifier.size(20.dp)
                            )
                        }

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

                            DropdownMenu(
                                expanded = showMenu,
                                onDismissRequest = { showMenu = false },
                                modifier = Modifier.background(AppColors.SurfaceElevated)
                            ) {
                                // Pin/Unpin Menu Item
                                DropdownMenuItem(
                                    text = {
                                        Row(
                                            verticalAlignment = Alignment.CenterVertically,
                                            horizontalArrangement = Arrangement.spacedBy(Constants.Spacing.Small.dp)
                                        ) {
                                            Icon(
                                                Icons.Default.PushPin,
                                                contentDescription = null,
                                                tint = if (category.isPinned) AppColors.Warning else AppColors.OnSurfaceVariant,
                                                modifier = Modifier.size(18.dp)
                                            )
                                            Text(
                                                if (category.isPinned) "Lepas Pin" else "Pin Kategori",
                                                color = AppColors.OnSurface,
                                                fontSize = 14.sp
                                            )
                                        }
                                    },
                                    onClick = {
                                        onPin()
                                        showMenu = false
                                    }
                                )

                                HorizontalDivider(color = AppColors.Divider)

                                // Edit Menu Item
                                DropdownMenuItem(
                                    text = {
                                        Row(
                                            verticalAlignment = Alignment.CenterVertically,
                                            horizontalArrangement = Arrangement.spacedBy(Constants.Spacing.Small.dp)
                                        ) {
                                            Icon(
                                                Icons.Default.Edit,
                                                contentDescription = null,
                                                tint = AppColors.Primary,
                                                modifier = Modifier.size(18.dp)
                                            )
                                            Text(
                                                "Edit Kategori",
                                                color = AppColors.OnSurface,
                                                fontSize = 14.sp
                                            )
                                        }
                                    },
                                    onClick = {
                                        showMenu = false
                                        showEditDialog = true
                                    }
                                )

                                HorizontalDivider(color = AppColors.Divider)

                                // Delete Menu Item
                                DropdownMenuItem(
                                    text = {
                                        Row(
                                            verticalAlignment = Alignment.CenterVertically,
                                            horizontalArrangement = Arrangement.spacedBy(Constants.Spacing.Small.dp)
                                        ) {
                                            Icon(
                                                Icons.Default.Delete,
                                                contentDescription = null,
                                                tint = AppColors.Error,
                                                modifier = Modifier.size(18.dp)
                                            )
                                            Text(
                                                "Pindah ke Sampah",
                                                color = AppColors.OnSurface,
                                                fontSize = 14.sp
                                            )
                                        }
                                    },
                                    onClick = {
                                        showMenu = false
                                        showDeleteConfirm = true
                                    }
                                )
                            }
                        }
                    }
                }

                Spacer(modifier = Modifier.height(Constants.Spacing.Medium.dp))

                // Category Name
                Text(
                    category.name,
                    style = MaterialTheme.typography.titleLarge,
                    fontWeight = FontWeight.Bold,
                    color = AppColors.OnBackground,
                    fontSize = 18.sp
                )

                Spacer(modifier = Modifier.height(Constants.Spacing.ExtraSmall.dp))

                // Note Count dengan subtle styling
                Row(
                    verticalAlignment = Alignment.CenterVertically,
                    horizontalArrangement = Arrangement.spacedBy(4.dp)
                ) {
                    Icon(
                        Icons.Default.Description,
                        contentDescription = null,
                        tint = AppColors.OnSurfaceTertiary,
                        modifier = Modifier.size(14.dp)
                    )
                    Text(
                        "$noteCount catatan",
                        style = MaterialTheme.typography.bodySmall,
                        color = AppColors.OnSurfaceTertiary,
                        fontSize = 13.sp
                    )
                }
            }
        }
    }
}

@Composable
fun EditCategoryDialog(
    category: Category,
    onDismiss: () -> Unit,
    onSave: (String, Long, Long) -> Unit
) {
    var name by remember { mutableStateOf(category.name) }
    var selectedGradient by remember {
        mutableStateOf(
            Constants.CategoryColors.indexOfFirst {
                it.first == category.gradientStart && it.second == category.gradientEnd
            }.takeIf { it >= 0 } ?: 0
        )
    }

    AlertDialog(
        onDismissRequest = onDismiss,
        containerColor = AppColors.Surface,
        shape = RoundedCornerShape(Constants.Radius.Large.dp),
        title = {
            Text(
                "Edit Kategori",
                color = AppColors.OnBackground,
                fontWeight = FontWeight.Bold
            )
        },
        text = {
            Column {
                OutlinedTextField(
                    value = name,
                    onValueChange = { name = it },
                    label = {
                        Text(
                            "Nama Kategori",
                            color = AppColors.OnSurfaceVariant
                        )
                    },
                    modifier = Modifier.fillMaxWidth(),
                    colors = OutlinedTextFieldDefaults.colors(
                        focusedTextColor = AppColors.OnBackground,
                        unfocusedTextColor = AppColors.OnSurface,
                        focusedContainerColor = AppColors.SurfaceVariant,
                        unfocusedContainerColor = AppColors.SurfaceVariant,
                        cursorColor = AppColors.Primary,
                        focusedBorderColor = AppColors.Primary,
                        unfocusedBorderColor = AppColors.Border
                    ),
                    shape = RoundedCornerShape(Constants.Radius.Medium.dp)
                )

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

                Text(
                    "Pilih Warna:",
                    style = MaterialTheme.typography.bodyMedium,
                    color = AppColors.OnSurface,
                    fontWeight = FontWeight.SemiBold,
                    fontSize = 14.sp
                )

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

                // 8 colors in 2 rows
                Constants.CategoryColors.chunked(4).forEach { row ->
                    Row(
                        modifier = Modifier.fillMaxWidth(),
                        horizontalArrangement = Arrangement.spacedBy(12.dp)
                    ) {
                        row.forEachIndexed { _, gradient ->
                            val globalIndex = Constants.CategoryColors.indexOf(gradient)
                            val isSelected = selectedGradient == globalIndex

                            Box(
                                modifier = Modifier
                                    .weight(1f)
                                    .aspectRatio(1f)
                                    .clip(RoundedCornerShape(Constants.Radius.Medium.dp))
                                    .background(
                                        brush = Brush.linearGradient(
                                            colors = listOf(
                                                Color(gradient.first),
                                                Color(gradient.second)
                                            )
                                        )
                                    )
                                    .clickable { selectedGradient = globalIndex },
                                contentAlignment = Alignment.Center
                            ) {
                                this@Row.AnimatedVisibility(
                                    visible = isSelected,
                                    enter = scaleIn() + fadeIn(),
                                    exit = scaleOut() + fadeOut()
                                ) {
                                    Icon(
                                        Icons.Default.Check,
                                        contentDescription = null,
                                        tint = Color.White,
                                        modifier = Modifier.size(28.dp)
                                    )
                                }
                            }
                        }
                    }
                    Spacer(modifier = Modifier.height(12.dp))
                }
            }
        },
        confirmButton = {
            Button(
                onClick = {
                    if (name.isNotBlank()) {
                        val gradient = Constants.CategoryColors[selectedGradient]
                        onSave(name, gradient.first, gradient.second)
                    }
                },
                enabled = name.isNotBlank(),
                colors = ButtonDefaults.buttonColors(
                    containerColor = AppColors.Primary
                )
            ) {
                Text("Simpan", color = Color.White, fontWeight = FontWeight.Bold)
            }
        },
        dismissButton = {
            TextButton(onClick = onDismiss) {
                Text("Batal", color = AppColors.OnSurfaceVariant)
            }
        }
    )
}