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

import androidx.compose.animation.*
import androidx.compose.animation.core.*
import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.background
import androidx.compose.foundation.combinedClickable
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.draw.rotate
import androidx.compose.ui.draw.scale
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextOverflow
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
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.*

@OptIn(ExperimentalFoundationApi::class)
@Composable
fun NoteCard(
    note: Note,
    onClick: () -> Unit,
    onPinClick: () -> Unit,
    onEdit: () -> Unit = {},
    onDelete: () -> Unit = {}
) {
    val dateFormat = SimpleDateFormat("dd MMM, HH:mm", Locale("id", "ID"))
    var showMenu by remember { mutableStateOf(false) }
    var showDeleteConfirm by remember { mutableStateOf(false) }

    // Scale animation on press
    var isPressed by remember { mutableStateOf(false) }
    val scale by animateFloatAsState(
        targetValue = if (isPressed) 0.95f else 1f,
        animationSpec = spring(
            dampingRatio = Spring.DampingRatioMediumBouncy,
            stiffness = Spring.StiffnessLow
        ),
        label = "scale"
    )

    // Pin icon rotation animation
    val pinRotation by animateFloatAsState(
        targetValue = if (note.isPinned) 0f else 45f,
        animationSpec = spring(
            dampingRatio = Spring.DampingRatioMediumBouncy,
            stiffness = Spring.StiffnessMedium
        ),
        label = "rotation"
    )

    // Elevation animation for pinned state
    val elevation by animateDpAsState(
        targetValue = if (note.isPinned) Constants.Elevation.Medium.dp else Constants.Elevation.Small.dp,
        animationSpec = spring(dampingRatio = Spring.DampingRatioMediumBouncy),
        label = "elevation"
    )

    // Delete Confirmation Dialog
    if (showDeleteConfirm) {
        AlertDialog(
            onDismissRequest = { showDeleteConfirm = false },
            icon = {
                Icon(
                    Icons.Default.DeleteForever,
                    contentDescription = null,
                    tint = AppColors.Error,
                    modifier = Modifier.size(32.dp)
                )
            },
            title = {
                Text(
                    "Pindahkan ke Sampah?",
                    color = AppColors.OnBackground,
                    fontWeight = FontWeight.Bold
                )
            },
            text = {
                Text(
                    "Catatan '${note.title}' 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)
        )
    }

    Card(
        modifier = Modifier
            .fillMaxWidth()
            .scale(scale)
            .combinedClickable(onClick = onClick),
        shape = RoundedCornerShape(Constants.Radius.Large.dp),
        colors = CardDefaults.cardColors(
            containerColor = if (note.isPinned)
                AppColors.SurfaceVariant.copy(alpha = 0.95f)
            else
                AppColors.SurfaceVariant
        ),
        elevation = CardDefaults.cardElevation(
            defaultElevation = elevation
        )
    ) {
        Column(
            modifier = Modifier
                .fillMaxWidth()
                .padding(Constants.Spacing.Large.dp)
        ) {
            // Header: Title + Menu
            Row(
                modifier = Modifier.fillMaxWidth(),
                horizontalArrangement = Arrangement.SpaceBetween,
                verticalAlignment = Alignment.Top
            ) {
                // Title with pin badge
                Row(
                    modifier = Modifier.weight(1f),
                    verticalAlignment = Alignment.CenterVertically,
                    horizontalArrangement = Arrangement.spacedBy(8.dp)
                ) {
                    Text(
                        note.title,
                        style = MaterialTheme.typography.titleLarge,
                        fontWeight = FontWeight.Bold,
                        color = AppColors.OnBackground,
                        maxLines = 2,
                        overflow = TextOverflow.Ellipsis,
                        fontSize = 18.sp,
                        modifier = Modifier.weight(1f, fill = false)
                    )

                    // Pin Badge next to title
                    AnimatedVisibility(
                        visible = note.isPinned,
                        enter = scaleIn(spring(dampingRatio = Spring.DampingRatioMediumBouncy)) + fadeIn(),
                        exit = scaleOut(spring(dampingRatio = Spring.DampingRatioMediumBouncy)) + fadeOut()
                    ) {
                        Surface(
                            color = AppColors.Warning.copy(alpha = 0.2f),
                            shape = RoundedCornerShape(Constants.Radius.Small.dp)
                        ) {
                            Row(
                                verticalAlignment = Alignment.CenterVertically,
                                horizontalArrangement = Arrangement.spacedBy(4.dp),
                                modifier = Modifier.padding(horizontal = 6.dp, vertical = 3.dp)
                            ) {
                                Icon(
                                    Icons.Filled.PushPin,
                                    contentDescription = "Disematkan",
                                    tint = AppColors.Warning,
                                    modifier = Modifier
                                        .size(12.dp)
                                        .rotate(45f)
                                )
                                Text(
                                    "Pin",
                                    fontSize = 10.sp,
                                    fontWeight = FontWeight.Bold,
                                    color = AppColors.Warning
                                )
                            }
                        }
                    }
                }

                // 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 option
                        DropdownMenuItem(
                            text = {
                                Row(
                                    verticalAlignment = Alignment.CenterVertically,
                                    horizontalArrangement = Arrangement.spacedBy(Constants.Spacing.Small.dp)
                                ) {
                                    Icon(
                                        Icons.Filled.PushPin,
                                        contentDescription = null,
                                        tint = if (note.isPinned) AppColors.Warning else AppColors.Primary,
                                        modifier = Modifier
                                            .size(18.dp)
                                            .rotate(pinRotation)
                                    )
                                    Text(
                                        if (note.isPinned) "Lepas Sematan" else "Sematkan",
                                        color = AppColors.OnSurface,
                                        fontSize = 14.sp
                                    )
                                }
                            },
                            onClick = {
                                showMenu = false
                                onPinClick()
                            }
                        )

                        HorizontalDivider(color = AppColors.Divider)

                        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 Catatan",
                                        color = AppColors.OnSurface,
                                        fontSize = 14.sp
                                    )
                                }
                            },
                            onClick = {
                                showMenu = false
                                onEdit()
                            }
                        )

                        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
                            }
                        )
                    }
                }
            }

            // Description Preview
            if (note.description.isNotEmpty()) {
                Spacer(modifier = Modifier.height(12.dp))

                Text(
                    note.description,
                    style = MaterialTheme.typography.bodyMedium,
                    maxLines = 3,
                    overflow = TextOverflow.Ellipsis,
                    color = AppColors.OnSurfaceVariant,
                    lineHeight = 20.sp,
                    fontSize = 14.sp
                )
            } else {
                Spacer(modifier = Modifier.height(12.dp))

                Text(
                    "Tidak ada deskripsi",
                    style = MaterialTheme.typography.bodyMedium,
                    color = AppColors.OnSurfaceVariant.copy(alpha = 0.5f),
                    fontStyle = androidx.compose.ui.text.font.FontStyle.Italic,
                    fontSize = 14.sp
                )
            }

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

            // Divider
            HorizontalDivider(
                color = AppColors.Divider,
                thickness = 1.dp
            )

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

            // Footer: Timestamp
            Row(
                modifier = Modifier.fillMaxWidth(),
                horizontalArrangement = Arrangement.SpaceBetween,
                verticalAlignment = Alignment.CenterVertically
            ) {
                Text(
                    dateFormat.format(Date(note.timestamp)),
                    style = MaterialTheme.typography.bodySmall,
                    color = AppColors.OnSurfaceTertiary,
                    fontSize = 12.sp
                )

                // Pin indicator icon in footer
                AnimatedVisibility(
                    visible = note.isPinned,
                    enter = fadeIn() + expandHorizontally(),
                    exit = fadeOut() + shrinkHorizontally()
                ) {
                    Icon(
                        Icons.Filled.PushPin,
                        contentDescription = "Disematkan",
                        tint = AppColors.Warning.copy(alpha = 0.6f),
                        modifier = Modifier
                            .size(14.dp)
                            .rotate(45f)
                    )
                }
            }
        }
    }
}