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

import androidx.compose.foundation.ExperimentalFoundationApi
import androidx.compose.foundation.background
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.pager.HorizontalPager
import androidx.compose.foundation.pager.rememberPagerState
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.material.icons.automirrored.filled.List
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.graphics.vector.ImageVector
import androidx.compose.ui.platform.testTag
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import com.tt.honeyDue.models.TaskColumn
import com.tt.honeyDue.models.TaskDetail
import com.tt.honeyDue.testing.AccessibilityIds
import com.tt.honeyDue.ui.theme.AppRadius
import com.tt.honeyDue.ui.theme.AppSpacing

@OptIn(ExperimentalFoundationApi::class)
@Composable
fun TaskKanbanView(
    upcomingTasks: List<TaskDetail>,
    inProgressTasks: List<TaskDetail>,
    doneTasks: List<TaskDetail>,
    archivedTasks: List<TaskDetail>,
    onCompleteTask: (TaskDetail) -> Unit,
    onEditTask: (TaskDetail) -> Unit,
    onCancelTask: ((TaskDetail) -> Unit)?,
    onUncancelTask: ((TaskDetail) -> Unit)?,
    onMarkInProgress: ((TaskDetail) -> Unit)?,
    onArchiveTask: ((TaskDetail) -> Unit)?,
    onUnarchiveTask: ((TaskDetail) -> Unit)?
) {
    val pagerState = rememberPagerState(pageCount = { 4 })

    Column(modifier = Modifier.fillMaxSize()) {
        HorizontalPager(
            state = pagerState,
            modifier = Modifier.fillMaxSize(),
            pageSpacing = 16.dp,
            contentPadding = PaddingValues(start = 16.dp, end = 48.dp)
        ) { page ->
            when (page) {
                0 -> TaskColumn(
                    title = "Upcoming",
                    icon = Icons.Default.CalendarToday,
                    color = MaterialTheme.colorScheme.primary,
                    count = upcomingTasks.size,
                    tasks = upcomingTasks,
                    onCompleteTask = onCompleteTask,
                    onEditTask = onEditTask,
                    onCancelTask = onCancelTask,
                    onUncancelTask = onUncancelTask,
                    onMarkInProgress = onMarkInProgress,
                    onArchiveTask = onArchiveTask,
                    onUnarchiveTask = null
                )
                1 -> TaskColumn(
                    title = "In Progress",
                    icon = Icons.Default.PlayCircle,
                    color = MaterialTheme.colorScheme.tertiary,
                    count = inProgressTasks.size,
                    tasks = inProgressTasks,
                    onCompleteTask = onCompleteTask,
                    onEditTask = onEditTask,
                    onCancelTask = onCancelTask,
                    onUncancelTask = onUncancelTask,
                    onMarkInProgress = null,
                    onArchiveTask = onArchiveTask,
                    onUnarchiveTask = null
                )
                2 -> TaskColumn(
                    title = "Done",
                    icon = Icons.Default.CheckCircle,
                    color = MaterialTheme.colorScheme.secondary,
                    count = doneTasks.size,
                    tasks = doneTasks,
                    onCompleteTask = null,
                    onEditTask = onEditTask,
                    onCancelTask = null,
                    onUncancelTask = null,
                    onMarkInProgress = null,
                    onArchiveTask = onArchiveTask,
                    onUnarchiveTask = null
                )
                3 -> TaskColumn(
                    title = "Archived",
                    icon = Icons.Default.Archive,
                    color = MaterialTheme.colorScheme.outline,
                    count = archivedTasks.size,
                    tasks = archivedTasks,
                    onCompleteTask = null,
                    onEditTask = onEditTask,
                    onCancelTask = null,
                    onUncancelTask = null,
                    onMarkInProgress = null,
                    onArchiveTask = null,
                    onUnarchiveTask = onUnarchiveTask
                )
            }
        }
    }
}

@Composable
private fun TaskColumn(
    title: String,
    icon: ImageVector,
    color: Color,
    count: Int,
    tasks: List<TaskDetail>,
    onCompleteTask: ((TaskDetail) -> Unit)?,
    onEditTask: (TaskDetail) -> Unit,
    onCancelTask: ((TaskDetail) -> Unit)?,
    onUncancelTask: ((TaskDetail) -> Unit)?,
    onMarkInProgress: ((TaskDetail) -> Unit)?,
    onArchiveTask: ((TaskDetail) -> Unit)?,
    onUnarchiveTask: ((TaskDetail) -> Unit)?
) {
    Column(
        modifier = Modifier
            .fillMaxSize()
            .background(
                MaterialTheme.colorScheme.surface,
                shape = RoundedCornerShape(AppRadius.md)
            )
    ) {
        // Header
        Row(
            modifier = Modifier
                .fillMaxWidth()
                .padding(AppSpacing.lg),
            horizontalArrangement = Arrangement.SpaceBetween,
            verticalAlignment = Alignment.CenterVertically
        ) {
            Row(
                horizontalArrangement = Arrangement.spacedBy(AppSpacing.sm),
                verticalAlignment = Alignment.CenterVertically
            ) {
                Icon(
                    imageVector = icon,
                    contentDescription = null, // decorative
                    tint = color,
                    modifier = Modifier.size(24.dp)
                )
                Text(
                    text = title,
                    style = MaterialTheme.typography.titleMedium,
                    fontWeight = FontWeight.Bold,
                    color = color
                )
            }

            Surface(
                color = color,
                shape = CircleShape
            ) {
                Text(
                    text = count.toString(),
                    modifier = Modifier.padding(horizontal = 10.dp, vertical = 4.dp),
                    style = MaterialTheme.typography.labelMedium,
                    fontWeight = FontWeight.Bold,
                    color = MaterialTheme.colorScheme.surface
                )
            }
        }

        // Tasks List
        if (tasks.isEmpty()) {
            Column(
                modifier = Modifier
                    .fillMaxSize()
                    .padding(32.dp),
                horizontalAlignment = Alignment.CenterHorizontally,
                verticalArrangement = Arrangement.Center
            ) {
                Icon(
                    imageVector = icon,
                    contentDescription = null, // decorative
                    tint = color.copy(alpha = 0.3f),
                    modifier = Modifier.size(48.dp)
                )
                Spacer(modifier = Modifier.height(AppSpacing.sm))
                Text(
                    text = "No tasks",
                    style = MaterialTheme.typography.bodyMedium,
                    color = MaterialTheme.colorScheme.onSurfaceVariant
                )
            }
        } else {
            // State for completion history sheet
            var selectedTaskForHistory by remember { mutableStateOf<TaskDetail?>(null) }

            LazyColumn(
                modifier = Modifier.fillMaxSize(),
                contentPadding = PaddingValues(AppSpacing.lg),
                verticalArrangement = Arrangement.spacedBy(AppSpacing.md)
            ) {
                items(tasks, key = { it.id }) { task ->
                    TaskCard(
                        task = task,
                        onCompleteClick = if (onCompleteTask != null) {
                            { onCompleteTask(task) }
                        } else null,
                        onEditClick = { onEditTask(task) },
                        onCancelClick = if (onCancelTask != null) {
                            { onCancelTask(task) }
                        } else null,
                        onUncancelClick = if (onUncancelTask != null) {
                            { onUncancelTask(task) }
                        } else null,
                        onMarkInProgressClick = if (onMarkInProgress != null) {
                            { onMarkInProgress(task) }
                        } else null,
                        onArchiveClick = if (onArchiveTask != null) {
                            { onArchiveTask(task) }
                        } else null,
                        onUnarchiveClick = if (onUnarchiveTask != null) {
                            { onUnarchiveTask(task) }
                        } else null,
                        onCompletionHistoryClick = if (task.completionCount > 0) {
                            { selectedTaskForHistory = task }
                        } else null
                    )
                }
            }

            // Completion history sheet
            selectedTaskForHistory?.let { task ->
                CompletionHistorySheet(
                    taskId = task.id,
                    taskTitle = task.title,
                    onDismiss = { selectedTaskForHistory = null }
                )
            }
        }
    }
}

/**
 * Dynamic Task Kanban View that creates columns based on API response
 */
@OptIn(ExperimentalFoundationApi::class)
@Composable
fun DynamicTaskKanbanView(
    columns: List<TaskColumn>,
    onCompleteTask: (TaskDetail) -> Unit,
    onEditTask: (TaskDetail) -> Unit,
    onCancelTask: ((TaskDetail) -> Unit)?,
    onUncancelTask: ((TaskDetail) -> Unit)?,
    onMarkInProgress: ((TaskDetail) -> Unit)?,
    onArchiveTask: ((TaskDetail) -> Unit)?,
    onUnarchiveTask: ((TaskDetail) -> Unit)?,
    modifier: Modifier = Modifier,
    bottomPadding: androidx.compose.ui.unit.Dp = 0.dp,
    scrollToColumnIndex: Int? = null,
    onScrollComplete: () -> Unit = {}
) {
    val pagerState = rememberPagerState(pageCount = { columns.size })

    // Handle scrolling to a specific column when requested (e.g., from push notification)
    LaunchedEffect(scrollToColumnIndex) {
        if (scrollToColumnIndex != null && scrollToColumnIndex in columns.indices) {
            pagerState.animateScrollToPage(scrollToColumnIndex)
            onScrollComplete()
        }
    }

    HorizontalPager(
        state = pagerState,
        modifier = modifier.fillMaxSize().testTag(AccessibilityIds.Task.kanbanView),
        pageSpacing = 16.dp,
        contentPadding = PaddingValues(start = 16.dp, end = 48.dp)
    ) { page ->
        val column = columns[page]
        DynamicTaskColumn(
            column = column,
            onCompleteTask = onCompleteTask,
            onEditTask = onEditTask,
            onCancelTask = onCancelTask,
            onUncancelTask = onUncancelTask,
            onMarkInProgress = onMarkInProgress,
            onArchiveTask = onArchiveTask,
            onUnarchiveTask = onUnarchiveTask,
            bottomPadding = bottomPadding
        )
    }
}

/**
 * Dynamic Task Column that adapts based on column configuration
 */
@Composable
private fun DynamicTaskColumn(
    column: TaskColumn,
    onCompleteTask: (TaskDetail) -> Unit,
    onEditTask: (TaskDetail) -> Unit,
    onCancelTask: ((TaskDetail) -> Unit)?,
    onUncancelTask: ((TaskDetail) -> Unit)?,
    onMarkInProgress: ((TaskDetail) -> Unit)?,
    onArchiveTask: ((TaskDetail) -> Unit)?,
    onUnarchiveTask: ((TaskDetail) -> Unit)?,
    bottomPadding: androidx.compose.ui.unit.Dp = 0.dp
) {
    // Get icon from API response, with fallback
    val columnIcon = getIconFromName(column.icons["android"] ?: "List")

    val columnColor = hexToColor(column.color)

    Column(
        modifier = Modifier.fillMaxSize()
    ) {
        // Header
        Row(
            modifier = Modifier
                .fillMaxWidth()
                .padding(horizontal = AppSpacing.lg, vertical = AppSpacing.md),
            horizontalArrangement = Arrangement.SpaceBetween,
            verticalAlignment = Alignment.CenterVertically
        ) {
            Row(
                horizontalArrangement = Arrangement.spacedBy(AppSpacing.sm),
                verticalAlignment = Alignment.CenterVertically
            ) {
                Icon(
                    imageVector = columnIcon,
                    contentDescription = null, // decorative
                    tint = columnColor,
                    modifier = Modifier.size(24.dp)
                )
                Text(
                    text = column.displayName,
                    style = MaterialTheme.typography.titleMedium,
                    fontWeight = FontWeight.Bold,
                    color = columnColor
                )
            }

            Surface(
                color = columnColor,
                shape = CircleShape
            ) {
                Text(
                    text = column.count.toString(),
                    modifier = Modifier.padding(horizontal = 10.dp, vertical = 4.dp),
                    style = MaterialTheme.typography.labelMedium,
                    fontWeight = FontWeight.Bold,
                    color = MaterialTheme.colorScheme.surface
                )
            }
        }

        // Tasks List
        if (column.tasks.isEmpty()) {
            Column(
                modifier = Modifier
                    .fillMaxSize()
                    .padding(32.dp),
                horizontalAlignment = Alignment.CenterHorizontally,
                verticalArrangement = Arrangement.Center
            ) {
                Icon(
                    imageVector = columnIcon,
                    contentDescription = null, // decorative
                    tint = columnColor.copy(alpha = 0.3f),
                    modifier = Modifier.size(48.dp)
                )
                Spacer(modifier = Modifier.height(AppSpacing.sm))
                Text(
                    text = "No tasks",
                    style = MaterialTheme.typography.bodyMedium,
                    color = MaterialTheme.colorScheme.onSurfaceVariant
                )
            }
        } else {
            // State for completion history sheet
            var selectedTaskForHistory by remember { mutableStateOf<TaskDetail?>(null) }

            LazyColumn(
                modifier = Modifier.fillMaxSize(),
                contentPadding = PaddingValues(
                    start = 16.dp,
                    end = 16.dp,
                    top = 8.dp,
                    bottom = 16.dp + bottomPadding
                ),
                verticalArrangement = Arrangement.spacedBy(AppSpacing.lg)
            ) {
                items(column.tasks, key = { it.id }) { task ->
                    // Use existing TaskCard component with buttonTypes array
                    TaskCard(
                        task = task,
                        buttonTypes = column.buttonTypes,
                        onCompleteClick = { onCompleteTask(task) },
                        onEditClick = { onEditTask(task) },
                        onCancelClick = onCancelTask?.let { { it(task) } },
                        onUncancelClick = onUncancelTask?.let { { it(task) } },
                        onMarkInProgressClick = onMarkInProgress?.let { { it(task) } },
                        onArchiveClick = onArchiveTask?.let { { it(task) } },
                        onUnarchiveClick = onUnarchiveTask?.let { { it(task) } },
                        onCompletionHistoryClick = if (task.completionCount > 0) {
                            { selectedTaskForHistory = task }
                        } else null
                    )
                }
            }

            // Completion history sheet
            selectedTaskForHistory?.let { task ->
                CompletionHistorySheet(
                    taskId = task.id,
                    taskTitle = task.title,
                    onDismiss = { selectedTaskForHistory = null }
                )
            }
        }
    }
}

/**
 * Helper function to convert icon name string to ImageVector
 */
private fun getIconFromName(iconName: String): ImageVector {
    return when (iconName) {
        "CalendarToday" -> Icons.Default.CalendarToday
        "PlayCircle" -> Icons.Default.PlayCircle
        "CheckCircle" -> Icons.Default.CheckCircle
        "Archive" -> Icons.Default.Archive
        "List" -> Icons.AutoMirrored.Filled.List
        "PlayArrow" -> Icons.Default.PlayArrow
        "Unarchive" -> Icons.Default.Unarchive
        else -> Icons.AutoMirrored.Filled.List // Default fallback
    }
}

/**
 * Helper function to convert hex color string to Color
 * Supports formats: #RGB, #RRGGBB, #AARRGGBB
 * Platform-independent implementation
 */
private fun hexToColor(hex: String): Color {
    val cleanHex = hex.removePrefix("#")
    return try {
        when (cleanHex.length) {
            3 -> {
                // RGB format - expand to RRGGBB
                val r = cleanHex[0].toString().repeat(2).toInt(16)
                val g = cleanHex[1].toString().repeat(2).toInt(16)
                val b = cleanHex[2].toString().repeat(2).toInt(16)
                Color(red = r / 255f, green = g / 255f, blue = b / 255f)
            }
            6 -> {
                // RRGGBB format
                val r = cleanHex.substring(0, 2).toInt(16)
                val g = cleanHex.substring(2, 4).toInt(16)
                val b = cleanHex.substring(4, 6).toInt(16)
                Color(red = r / 255f, green = g / 255f, blue = b / 255f)
            }
            8 -> {
                // AARRGGBB format
                val a = cleanHex.substring(0, 2).toInt(16)
                val r = cleanHex.substring(2, 4).toInt(16)
                val g = cleanHex.substring(4, 6).toInt(16)
                val b = cleanHex.substring(6, 8).toInt(16)
                Color(red = r / 255f, green = g / 255f, blue = b / 255f, alpha = a / 255f)
            }
            else -> Color.Gray // Default fallback
        }
    } catch (e: Exception) {
        Color.Gray // Fallback on parse error
    }
}
