package com.tt.honeyDue.ui.components.task

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.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.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.testTag
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import honeydue.composeapp.generated.resources.*
import com.tt.honeyDue.testing.AccessibilityIds
import com.tt.honeyDue.models.TaskDetail
import com.tt.honeyDue.models.TaskCategory
import com.tt.honeyDue.models.TaskPriority
import com.tt.honeyDue.models.TaskFrequency
import com.tt.honeyDue.models.TaskCompletion
import com.tt.honeyDue.util.DateUtils
import com.tt.honeyDue.ui.theme.AppRadius
import com.tt.honeyDue.ui.theme.AppSpacing
import org.jetbrains.compose.resources.stringResource
import org.jetbrains.compose.ui.tooling.preview.Preview

@OptIn(ExperimentalFoundationApi::class)
@Composable
fun TaskCard(
    task: TaskDetail,
    buttonTypes: List<String> = emptyList(),
    onCompleteClick: (() -> Unit)?,
    onEditClick: (() -> Unit)?,
    onCancelClick: (() -> Unit)?,
    onUncancelClick: (() -> Unit)?,
    onMarkInProgressClick: (() -> Unit)? = null,
    onArchiveClick: (() -> Unit)? = null,
    onUnarchiveClick: (() -> Unit)? = null,
    onCompletionHistoryClick: (() -> Unit)? = null,
    onClick: (() -> Unit)? = null,
    onLongPressEdit: (() -> Unit)? = null,
    onLongPressDelete: (() -> Unit)? = null,
    onLongPressShare: (() -> Unit)? = null
) {
    var showContextMenu by remember { mutableStateOf(false) }
    Card(
        modifier = Modifier
            .fillMaxWidth()
            .testTag(AccessibilityIds.Task.taskCard)
            .combinedClickable(
                onClick = { onClick?.invoke() },
                onLongClick = {
                    if (onLongPressEdit != null || onLongPressDelete != null || onLongPressShare != null) {
                        showContextMenu = true
                    }
                }
            ),
        shape = RoundedCornerShape(AppRadius.md),
        elevation = CardDefaults.cardElevation(defaultElevation = 4.dp),
        colors = CardDefaults.cardColors(
            containerColor = MaterialTheme.colorScheme.surfaceContainerHigh
        )
    ) {
        Column(
            modifier = Modifier
                .fillMaxWidth()
                .padding(20.dp)
        ) {
            Row(
                modifier = Modifier.fillMaxWidth(),
                horizontalArrangement = Arrangement.SpaceBetween,
                verticalAlignment = Alignment.CenterVertically
            ) {
                Column(modifier = Modifier.weight(1f)) {
                    Text(
                        text = task.title,
                        style = MaterialTheme.typography.titleMedium,
                        color = MaterialTheme.colorScheme.onSurface
                    )
                    Spacer(modifier = Modifier.height(AppSpacing.sm))
                    // Pill-style category badge
                    Surface(
                        color = MaterialTheme.colorScheme.surfaceVariant,
                        shape = RoundedCornerShape(AppRadius.md)
                    ) {
                        Text(
                            text = (task.category?.name ?: "").uppercase(),
                            modifier = Modifier.padding(horizontal = AppSpacing.md, vertical = 6.dp),
                            style = MaterialTheme.typography.labelSmall,
                            color = MaterialTheme.colorScheme.onSurfaceVariant
                        )
                    }
                }

                Column(
                    horizontalAlignment = Alignment.End,
                    verticalArrangement = Arrangement.spacedBy(AppSpacing.sm)
                ) {
                    // Priority badge with semantic colors
                    val priorityColor = when (task.priority?.name?.lowercase()) {
                        "urgent", "high" -> MaterialTheme.colorScheme.error
                        "medium" -> MaterialTheme.colorScheme.tertiary
                        else -> MaterialTheme.colorScheme.secondary
                    }
                    Row(
                        modifier = Modifier
                            .background(
                                priorityColor.copy(alpha = 0.15f),
                                RoundedCornerShape(AppRadius.md)
                            )
                            .padding(horizontal = AppSpacing.md, vertical = 6.dp),
                        horizontalArrangement = Arrangement.spacedBy(AppSpacing.xs),
                        verticalAlignment = Alignment.CenterVertically
                    ) {
                        Box(
                            modifier = Modifier
                                .size(6.dp)
                                .clip(CircleShape)
                                .background(priorityColor)
                        )
                        Text(
                            text = (task.priority?.name ?: "").uppercase(),
                            style = MaterialTheme.typography.labelSmall,
                            color = priorityColor
                        )
                    }

                    // In Progress badge
                    if (task.inProgress) {
                        val statusColor = MaterialTheme.colorScheme.tertiary
                        Surface(
                            color = statusColor.copy(alpha = 0.15f),
                            shape = RoundedCornerShape(AppRadius.md)
                        ) {
                            Text(
                                text = stringResource(Res.string.tasks_card_in_progress),
                                modifier = Modifier.padding(horizontal = AppSpacing.md, vertical = 6.dp),
                                style = MaterialTheme.typography.labelSmall,
                                color = statusColor
                            )
                        }
                    }
                }
            }

            if (task.description != null) {
                Spacer(modifier = Modifier.height(AppSpacing.md))
                Text(
                    text = task.description,
                    style = MaterialTheme.typography.bodyMedium,
                    color = MaterialTheme.colorScheme.onSurfaceVariant
                )
            }

            Spacer(modifier = Modifier.height(AppSpacing.lg))
            HorizontalDivider(color = MaterialTheme.colorScheme.outlineVariant)
            Spacer(modifier = Modifier.height(AppSpacing.lg))

            // Metadata pills
            Row(
                modifier = Modifier.fillMaxWidth(),
                horizontalArrangement = Arrangement.spacedBy(AppSpacing.md)
            ) {
                // Date pill
                Row(
                    modifier = Modifier
                        .background(
                            MaterialTheme.colorScheme.surfaceVariant,
                            RoundedCornerShape(AppRadius.md)
                        )
                        .padding(horizontal = AppSpacing.md, vertical = 6.dp),
                    verticalAlignment = Alignment.CenterVertically,
                    horizontalArrangement = Arrangement.spacedBy(6.dp)
                ) {
                    Icon(
                        Icons.Default.CalendarToday,
                        contentDescription = null, // decorative
                        modifier = Modifier.size(14.dp),
                        tint = MaterialTheme.colorScheme.onSurfaceVariant
                    )
                    Text(
                        text = DateUtils.formatDate(task.nextScheduledDate ?: task.dueDate) ?: stringResource(Res.string.tasks_card_not_available),
                        style = MaterialTheme.typography.labelSmall,
                        color = MaterialTheme.colorScheme.onSurfaceVariant
                    )
                }

                // Cost pill
                task.estimatedCost?.let {
                    Row(
                        modifier = Modifier
                            .background(
                                MaterialTheme.colorScheme.surfaceVariant,
                                RoundedCornerShape(AppRadius.md)
                            )
                            .padding(horizontal = AppSpacing.md, vertical = 6.dp),
                        verticalAlignment = Alignment.CenterVertically,
                        horizontalArrangement = Arrangement.spacedBy(6.dp)
                    ) {
                        Icon(
                            Icons.Default.AttachMoney,
                            contentDescription = null, // decorative
                            modifier = Modifier.size(14.dp),
                            tint = MaterialTheme.colorScheme.onSurfaceVariant
                        )
                        Text(
                            text = "$$it",
                            style = MaterialTheme.typography.labelSmall,
                            color = MaterialTheme.colorScheme.onSurfaceVariant
                        )
                    }
                }
            }

            // Actions row with completion count button and actions menu
            if (buttonTypes.isNotEmpty() || task.completionCount > 0) {
                var showActionsMenu by remember { mutableStateOf(false) }

                Spacer(modifier = Modifier.height(AppSpacing.lg))
                HorizontalDivider(color = MaterialTheme.colorScheme.outlineVariant)
                Spacer(modifier = Modifier.height(AppSpacing.lg))

                Row(
                    modifier = Modifier.fillMaxWidth(),
                    horizontalArrangement = Arrangement.spacedBy(AppSpacing.md)
                ) {
                     // Actions dropdown menu based on buttonTypes array
                    if (buttonTypes.isNotEmpty()) {
                        Box(modifier = Modifier.weight(1f)) {
                            Button(
                                onClick = { showActionsMenu = true },
                                modifier = Modifier.fillMaxWidth(),
                                colors = ButtonDefaults.buttonColors(
                                    containerColor = MaterialTheme.colorScheme.primaryContainer,
                                    contentColor = MaterialTheme.colorScheme.onPrimaryContainer
                                ),
                                shape = RoundedCornerShape(AppRadius.sm)
                            ) {
                                Icon(
                                    Icons.Default.MoreVert,
                                    contentDescription = null, // decorative
                                    modifier = Modifier.size(18.dp)
                                )
                                Spacer(modifier = Modifier.width(AppSpacing.sm))
                                Text(
                                    text = stringResource(Res.string.tasks_card_actions),
                                    style = MaterialTheme.typography.labelLarge,
                                    fontWeight = FontWeight.SemiBold
                                )
                            }

                            DropdownMenu(
                                expanded = showActionsMenu,
                                onDismissRequest = { showActionsMenu = false }
                            ) {
                                // Primary actions
                                buttonTypes.filter { isPrimaryAction(it) }.forEach { buttonType ->
                                    getActionMenuItem(
                                        buttonType = buttonType,
                                        task = task,
                                        onMarkInProgressClick = onMarkInProgressClick,
                                        onCompleteClick = onCompleteClick,
                                        onEditClick = onEditClick,
                                        onUncancelClick = onUncancelClick,
                                        onUnarchiveClick = onUnarchiveClick,
                                        onDismiss = { showActionsMenu = false }
                                    )
                                }

                                // Secondary actions
                                if (buttonTypes.any { isSecondaryAction(it) }) {
                                    HorizontalDivider()
                                    buttonTypes.filter { isSecondaryAction(it) }.forEach { buttonType ->
                                        getActionMenuItem(
                                            buttonType = buttonType,
                                            task = task,
                                            onArchiveClick = onArchiveClick,
                                            onDismiss = { showActionsMenu = false }
                                        )
                                    }
                                }

                                // Destructive actions
                                if (buttonTypes.any { isDestructiveAction(it) }) {
                                    HorizontalDivider()
                                    buttonTypes.filter { isDestructiveAction(it) }.forEach { buttonType ->
                                        getActionMenuItem(
                                            buttonType = buttonType,
                                            task = task,
                                            onCancelClick = onCancelClick,
                                            onDismiss = { showActionsMenu = false }
                                        )
                                    }
                                }
                            }
                        }
                    }

                    // Completion count button - shows when count > 0
                    if (task.completionCount > 0) {
                        Button(
                            onClick = { onCompletionHistoryClick?.invoke() },
                            colors = ButtonDefaults.buttonColors(
                                containerColor = MaterialTheme.colorScheme.tertiaryContainer,
                                contentColor = MaterialTheme.colorScheme.onTertiaryContainer
                            ),
                            shape = RoundedCornerShape(AppRadius.sm)
                        ) {
                            Icon(
                                Icons.Default.CheckCircle,
                                contentDescription = null, // decorative
                                modifier = Modifier.size(18.dp)
                            )
                            Spacer(modifier = Modifier.width(6.dp))
                            Text(
                                text = "${task.completionCount}",
                                style = MaterialTheme.typography.labelLarge,
                                fontWeight = FontWeight.Bold
                            )
                        }
                    }
                }
            }

            // Long-press context menu
            Box {
                DropdownMenu(
                    expanded = showContextMenu,
                    onDismissRequest = { showContextMenu = false },
                    modifier = Modifier.testTag(AccessibilityIds.Task.contextMenu)
                ) {
                    onLongPressEdit?.let { handler ->
                        DropdownMenuItem(
                            text = { Text(stringResource(Res.string.tasks_card_edit_task)) },
                            leadingIcon = { Icon(Icons.Default.Edit, contentDescription = null) },
                            onClick = {
                                handler()
                                showContextMenu = false
                            }
                        )
                    }
                    onLongPressShare?.let { handler ->
                        DropdownMenuItem(
                            text = { Text(stringResource(Res.string.common_share)) },
                            leadingIcon = { Icon(Icons.Default.Share, contentDescription = null) },
                            onClick = {
                                handler()
                                showContextMenu = false
                            }
                        )
                    }
                    onLongPressDelete?.let { handler ->
                        DropdownMenuItem(
                            text = { Text(stringResource(Res.string.common_delete)) },
                            leadingIcon = {
                                Icon(
                                    Icons.Default.Delete,
                                    contentDescription = null,
                                    tint = MaterialTheme.colorScheme.error
                                )
                            },
                            onClick = {
                                handler()
                                showContextMenu = false
                            }
                        )
                    }
                }
            }
        }
    }
}

// Helper functions for action classification
private fun isPrimaryAction(buttonType: String): Boolean {
    return buttonType in listOf("mark_in_progress", "complete", "edit", "uncancel", "unarchive")
}

private fun isSecondaryAction(buttonType: String): Boolean {
    return buttonType == "archive"
}

private fun isDestructiveAction(buttonType: String): Boolean {
    return buttonType == "cancel"
}

@Composable
private fun getActionMenuItem(
    buttonType: String,
    task: TaskDetail,
    onMarkInProgressClick: (() -> Unit)? = null,
    onCompleteClick: (() -> Unit)? = null,
    onEditClick: (() -> Unit)? = null,
    onCancelClick: (() -> Unit)? = null,
    onUncancelClick: (() -> Unit)? = null,
    onArchiveClick: (() -> Unit)? = null,
    onUnarchiveClick: (() -> Unit)? = null,
    onDismiss: () -> Unit
) {
    when (buttonType) {
        "mark_in_progress" -> {
            onMarkInProgressClick?.let {
                DropdownMenuItem(
                    text = { Text(stringResource(Res.string.tasks_card_mark_in_progress)) },
                    leadingIcon = {
                        Icon(Icons.Default.PlayArrow, contentDescription = null) // decorative
                    },
                    onClick = {
                        it()
                        onDismiss()
                    }
                )
            }
        }
        "complete" -> {
            onCompleteClick?.let {
                DropdownMenuItem(
                    text = { Text(stringResource(Res.string.tasks_card_complete_task)) },
                    leadingIcon = {
                        Icon(Icons.Default.CheckCircle, contentDescription = null) // decorative
                    },
                    onClick = {
                        it()
                        onDismiss()
                    }
                )
            }
        }
        "edit" -> {
            onEditClick?.let {
                DropdownMenuItem(
                    text = { Text(stringResource(Res.string.tasks_card_edit_task)) },
                    leadingIcon = {
                        Icon(Icons.Default.Edit, contentDescription = null) // decorative
                    },
                    onClick = {
                        it()
                        onDismiss()
                    }
                )
            }
        }
        "cancel" -> {
            onCancelClick?.let {
                DropdownMenuItem(
                    text = { Text(stringResource(Res.string.tasks_card_cancel_task)) },
                    leadingIcon = {
                        Icon(
                            Icons.Default.Cancel,
                            contentDescription = null, // decorative
                            tint = MaterialTheme.colorScheme.error
                        )
                    },
                    onClick = {
                        it()
                        onDismiss()
                    }
                )
            }
        }
        "uncancel" -> {
            onUncancelClick?.let {
                DropdownMenuItem(
                    text = { Text(stringResource(Res.string.tasks_card_restore_task)) },
                    leadingIcon = {
                        Icon(Icons.Default.Undo, contentDescription = null) // decorative
                    },
                    onClick = {
                        it()
                        onDismiss()
                    }
                )
            }
        }
        "archive" -> {
            onArchiveClick?.let {
                DropdownMenuItem(
                    text = { Text(stringResource(Res.string.tasks_card_archive_task)) },
                    leadingIcon = {
                        Icon(Icons.Default.Archive, contentDescription = null) // decorative
                    },
                    onClick = {
                        it()
                        onDismiss()
                    }
                )
            }
        }
        "unarchive" -> {
            onUnarchiveClick?.let {
                DropdownMenuItem(
                    text = { Text(stringResource(Res.string.tasks_card_unarchive_task)) },
                    leadingIcon = {
                        Icon(Icons.Default.Unarchive, contentDescription = null) // decorative
                    },
                    onClick = {
                        it()
                        onDismiss()
                    }
                )
            }
        }
    }
}

@Composable
fun CompletionCard(completion: TaskCompletion) {
    var showPhotoDialog by remember { mutableStateOf(false) }

    val hasImages = !completion.images.isNullOrEmpty()
    println("CompletionCard: hasImages = $hasImages, images count = ${completion.images?.size ?: 0}")

    Card(
        colors = CardDefaults.cardColors(
            containerColor = MaterialTheme.colorScheme.surfaceVariant
        ),
        shape = MaterialTheme.shapes.medium,
        elevation = CardDefaults.cardElevation(defaultElevation = 0.dp)
    ) {
        Column(
            modifier = Modifier
                .fillMaxWidth()
                .padding(AppSpacing.lg)
        ) {
            Row(
                modifier = Modifier.fillMaxWidth(),
                horizontalArrangement = Arrangement.SpaceBetween,
                verticalAlignment = Alignment.CenterVertically
            ) {
                Text(
                    text = completion.completionDate.split("T")[0],
                    style = MaterialTheme.typography.bodyMedium,
                    fontWeight = FontWeight.Bold,
                    color = MaterialTheme.colorScheme.primary
                )
                completion.rating?.let { rating ->
                    Surface(
                        color = MaterialTheme.colorScheme.tertiaryContainer,
                        shape = RoundedCornerShape(AppRadius.sm)
                    ) {
                        Text(
                            text = "$rating★",
                            modifier = Modifier.padding(horizontal = AppSpacing.sm, vertical = AppSpacing.xs),
                            style = MaterialTheme.typography.labelMedium,
                            fontWeight = FontWeight.Bold,
                            color = MaterialTheme.colorScheme.onTertiaryContainer
                        )
                    }
                }
            }

            // Display contractor or manual entry
            completion.contractorDetails?.let { contractor ->
                Spacer(modifier = Modifier.height(AppSpacing.sm))
                Row(verticalAlignment = Alignment.CenterVertically) {
                    Icon(
                        Icons.Default.Build,
                        contentDescription = null, // decorative
                        modifier = Modifier.size(16.dp),
                        tint = MaterialTheme.colorScheme.primary
                    )
                    Spacer(modifier = Modifier.width(AppSpacing.xs))
                    Column {
                        Text(
                            text = stringResource(Res.string.tasks_card_completed_by, contractor.name),
                            style = MaterialTheme.typography.bodySmall,
                            fontWeight = FontWeight.Medium
                        )
                        contractor.company?.let { company ->
                            Text(
                                text = company,
                                style = MaterialTheme.typography.bodySmall,
                                color = MaterialTheme.colorScheme.onSurfaceVariant
                            )
                        }
                    }
                }
            } ?: completion.completedByName?.let {
                Spacer(modifier = Modifier.height(AppSpacing.sm))
                Text(
                    text = stringResource(Res.string.tasks_card_completed_by, it),
                    style = MaterialTheme.typography.bodySmall,
                    fontWeight = FontWeight.Medium
                )
            }

            completion.actualCost?.let {
                Text(
                    text = stringResource(Res.string.tasks_card_cost, it.toString()),
                    style = MaterialTheme.typography.bodySmall,
                    color = MaterialTheme.colorScheme.tertiary,
                    fontWeight = FontWeight.Medium
                )
            }

            completion.notes?.let {
                Spacer(modifier = Modifier.height(AppSpacing.sm))
                Text(
                    text = it,
                    style = MaterialTheme.typography.bodySmall,
                    color = MaterialTheme.colorScheme.onSurfaceVariant
                )
            }

            // Show button to view photos if images exist
            if (hasImages) {
                Spacer(modifier = Modifier.height(AppSpacing.md))
                Button(
                    onClick = {
                        println("View Photos button clicked!")
                        showPhotoDialog = true
                    },
                    modifier = Modifier.fillMaxWidth(),
                    colors = ButtonDefaults.buttonColors(
                        containerColor = MaterialTheme.colorScheme.primaryContainer,
                        contentColor = MaterialTheme.colorScheme.onPrimaryContainer
                    )
                ) {
                    Icon(
                        Icons.Default.PhotoLibrary,
                        contentDescription = null, // decorative
                        modifier = Modifier.size(18.dp)
                    )
                    Spacer(modifier = Modifier.width(AppSpacing.sm))
                    Text(
                        text = stringResource(Res.string.tasks_card_view_photos, completion.images?.size ?: 0),
                        style = MaterialTheme.typography.labelLarge,
                        fontWeight = FontWeight.SemiBold
                    )
                }
            }
        }
    }

    // Photo viewer dialog
    if (showPhotoDialog && hasImages) {
        println("Showing PhotoViewerDialog with ${completion.images?.size} images")
        PhotoViewerDialog(
            images = completion.images!!,
            onDismiss = {
                println("PhotoViewerDialog dismissed")
                showPhotoDialog = false
            }
        )
    }
}

@Preview
@Composable
fun TaskCardPreview() {
    MaterialTheme {
        TaskCard(
            task = TaskDetail(
                id = 1,
                residenceId = 1,
                createdById = 1,
                title = "Clean Gutters",
                description = "Remove all debris from gutters and downspouts",
                category = TaskCategory(id = 1, name = "maintenance"),
                priority = TaskPriority(id = 2, name = "medium"),
                frequency = TaskFrequency(
                    id = 1, name = "monthly", days = 30
                ),
                inProgress = false,
                dueDate = "2024-12-15",
                estimatedCost = 150.00,
                createdAt = "2024-01-01T00:00:00Z",
                updatedAt = "2024-01-01T00:00:00Z",
                completions = emptyList()
            ),
            onCompleteClick = {},
            onEditClick = {},
            onCancelClick = {},
            onUncancelClick = null
        )
    }
}
