package com.tt.honeyDue.ui.screens

import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.*
import androidx.compose.material.icons.automirrored.filled.ArrowBack
import androidx.compose.material3.*
import androidx.compose.material3.pulltorefresh.PullToRefreshBox
import androidx.compose.runtime.*
import androidx.compose.ui.Modifier
import androidx.compose.ui.unit.dp
import androidx.lifecycle.viewmodel.compose.viewModel
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import com.tt.honeyDue.ui.components.CompleteTaskDialog
import com.tt.honeyDue.ui.components.ErrorDialog
import com.tt.honeyDue.ui.components.task.TaskCard
import com.tt.honeyDue.ui.components.task.TaskPill
import com.tt.honeyDue.ui.utils.getIconFromName
import com.tt.honeyDue.ui.utils.hexToColor
import com.tt.honeyDue.viewmodel.TaskCompletionViewModel
import com.tt.honeyDue.viewmodel.TaskViewModel
import com.tt.honeyDue.network.ApiResult
import com.tt.honeyDue.analytics.PostHogAnalytics
import com.tt.honeyDue.analytics.AnalyticsEvents
import com.tt.honeyDue.ui.theme.*
import honeydue.composeapp.generated.resources.*
import org.jetbrains.compose.resources.stringResource

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun TasksScreen(
    onNavigateBack: () -> Unit,
    onAddTask: () -> Unit = {},
    viewModel: TaskViewModel = viewModel { TaskViewModel() },
    taskCompletionViewModel: TaskCompletionViewModel = viewModel { TaskCompletionViewModel() }
) {
    val tasksState by viewModel.tasksState.collectAsStateWithLifecycle()
    val completionState by taskCompletionViewModel.createCompletionState.collectAsStateWithLifecycle()
    var expandedColumns by remember { mutableStateOf(setOf<String>()) }
    var showCompleteDialog by remember { mutableStateOf(false) }
    var selectedTask by remember { mutableStateOf<com.tt.honeyDue.models.TaskDetail?>(null) }
    var showErrorDialog by remember { mutableStateOf(false) }
    var errorMessage by remember { mutableStateOf("") }
    var isRefreshing by remember { mutableStateOf(false) }

    // Show error dialog when tasks fail to load
    LaunchedEffect(tasksState) {
        if (tasksState is ApiResult.Error) {
            errorMessage = com.tt.honeyDue.util.ErrorMessageParser.parse((tasksState as ApiResult.Error).message)
            showErrorDialog = true
        }
        if (tasksState !is ApiResult.Loading) {
            isRefreshing = false
        }
    }

    LaunchedEffect(Unit) {
        PostHogAnalytics.screen(AnalyticsEvents.TASK_SCREEN_SHOWN)
        viewModel.loadTasks()
    }

    // Handle completion success
    LaunchedEffect(completionState) {
        when (completionState) {
            is ApiResult.Success -> {
                showCompleteDialog = false
                selectedTask = null
                taskCompletionViewModel.resetCreateState()
                viewModel.loadTasks()
            }
            else -> {}
        }
    }

    WarmGradientBackground {
        Scaffold(
            containerColor = androidx.compose.ui.graphics.Color.Transparent,
            topBar = {
                TopAppBar(
                    title = { Text(stringResource(Res.string.tasks_title)) },
                    navigationIcon = {
                        IconButton(onClick = onNavigateBack) {
                            Icon(Icons.AutoMirrored.Filled.ArrowBack, contentDescription = stringResource(Res.string.common_back))
                        }
                    },
                    colors = TopAppBarDefaults.topAppBarColors(
                        containerColor = androidx.compose.ui.graphics.Color.Transparent
                    )
                )
            },
            // No FAB on Tasks screen - tasks are added from within residences
        ) { paddingValues ->
            when (tasksState) {
                is ApiResult.Idle, is ApiResult.Loading, is ApiResult.Error -> {
                    Box(
                        modifier = Modifier
                            .fillMaxSize()
                            .padding(paddingValues),
                        contentAlignment = androidx.compose.ui.Alignment.Center
                    ) {
                        CircularProgressIndicator(
                            color = MaterialTheme.colorScheme.primary
                        )
                    }
                }
                is ApiResult.Success -> {
                    val taskData = (tasksState as ApiResult.Success).data
                    val hasNoTasks = taskData.columns.all { it.tasks.isEmpty() }

                    if (hasNoTasks) {
                        Box(
                            modifier = Modifier
                                .fillMaxSize()
                                .padding(paddingValues),
                            contentAlignment = androidx.compose.ui.Alignment.Center
                        ) {
                            Column(
                                horizontalAlignment = androidx.compose.ui.Alignment.CenterHorizontally,
                                verticalArrangement = Arrangement.spacedBy(OrganicSpacing.cozy),
                                modifier = Modifier.padding(OrganicSpacing.comfortable)
                            ) {
                                OrganicIconContainer(
                                    icon = Icons.Default.Assignment,
                                    size = 80.dp,
                                    iconScale = 0.6f,
                                    backgroundColor = MaterialTheme.colorScheme.primary.copy(alpha = 0.2f),
                                    iconColor = MaterialTheme.colorScheme.primary
                                )
                                Text(
                                    stringResource(Res.string.tasks_empty_title),
                                    style = MaterialTheme.typography.headlineSmall,
                                    fontWeight = androidx.compose.ui.text.font.FontWeight.SemiBold,
                                    color = MaterialTheme.colorScheme.textPrimary
                                )
                                Text(
                                    stringResource(Res.string.tasks_empty_subtitle),
                                    style = MaterialTheme.typography.bodyLarge,
                                    color = MaterialTheme.colorScheme.textSecondary
                                )
                            }
                        }
                    } else {
                        PullToRefreshBox(
                            isRefreshing = isRefreshing,
                            onRefresh = {
                                isRefreshing = true
                                viewModel.loadTasks(forceRefresh = true)
                            },
                            modifier = Modifier
                                .fillMaxSize()
                                .padding(paddingValues)
                        ) {
                        LazyColumn(
                            modifier = Modifier
                                .fillMaxSize(),
                            contentPadding = PaddingValues(
                                top = OrganicSpacing.cozy,
                                bottom = OrganicSpacing.cozy,
                                start = OrganicSpacing.cozy,
                                end = OrganicSpacing.cozy
                            ),
                            verticalArrangement = Arrangement.spacedBy(OrganicSpacing.compact)
                        ) {
                            // Task summary pills - dynamically generated from all columns
                            item {
                                Row(
                                    modifier = Modifier.fillMaxWidth(),
                                    horizontalArrangement = Arrangement.spacedBy(OrganicSpacing.compact)
                                ) {
                                    taskData.columns.forEach { column ->
                                        TaskPill(
                                            count = column.count,
                                            label = column.displayName,
                                            color = hexToColor(column.color)
                                        )
                                    }
                                }
                            }

                            // Dynamically render all columns
                            taskData.columns.forEachIndexed { index, column ->
                                if (column.tasks.isNotEmpty()) {
                                    // First column (index 0) expanded by default, others collapsible
                                    if (index == 0) {
                                        // First column - always expanded, show tasks directly
                                        item {
                                            Text(
                                                text = "${column.displayName} (${column.tasks.size})",
                                                style = MaterialTheme.typography.titleMedium,
                                                color = MaterialTheme.colorScheme.textPrimary,
                                                modifier = Modifier.padding(top = OrganicSpacing.compact)
                                            )
                                        }

                                        items(column.tasks) { task ->
                                            TaskCard(
                                                task = task,
                                                onCompleteClick = {
                                                    selectedTask = task
                                                    showCompleteDialog = true
                                                },
                                                onEditClick = { },
                                                onCancelClick = { },
                                                onUncancelClick = { }
                                            )
                                        }
                                    } else {
                                        // Other columns - collapsible
                                        val isExpanded = expandedColumns.contains(column.name)

                                        item {
                                            OrganicCard(
                                                modifier = Modifier
                                                    .fillMaxWidth()
                                                    .clickable {
                                                        expandedColumns = if (isExpanded) {
                                                            expandedColumns - column.name
                                                        } else {
                                                            expandedColumns + column.name
                                                        }
                                                    },
                                                showBlob = false,
                                                shadowIntensity = ShadowIntensity.Subtle
                                            ) {
                                                Row(
                                                    modifier = Modifier
                                                        .fillMaxWidth()
                                                        .padding(OrganicSpacing.cozy),
                                                    horizontalArrangement = Arrangement.SpaceBetween,
                                                    verticalAlignment = androidx.compose.ui.Alignment.CenterVertically
                                                ) {
                                                    Row(
                                                        horizontalArrangement = Arrangement.spacedBy(OrganicSpacing.compact),
                                                        verticalAlignment = androidx.compose.ui.Alignment.CenterVertically
                                                    ) {
                                                        OrganicIconContainer(
                                                            icon = getIconFromName(column.icons["android"] ?: "List"),
                                                            size = 40.dp,
                                                            iconScale = 0.5f,
                                                            backgroundColor = hexToColor(column.color).copy(alpha = 0.2f),
                                                            iconColor = hexToColor(column.color)
                                                        )
                                                        Text(
                                                            text = "${column.displayName} (${column.tasks.size})",
                                                            style = MaterialTheme.typography.titleMedium,
                                                            color = MaterialTheme.colorScheme.textPrimary
                                                        )
                                                    }
                                                    Icon(
                                                        if (isExpanded) Icons.Default.KeyboardArrowUp else Icons.Default.KeyboardArrowDown,
                                                        contentDescription = if (isExpanded) "Collapse" else "Expand",
                                                        tint = MaterialTheme.colorScheme.textSecondary
                                                    )
                                                }
                                            }
                                        }

                                        if (isExpanded) {
                                            items(column.tasks) { task ->
                                                TaskCard(
                                                    task = task,
                                                    onCompleteClick = {
                                                        selectedTask = task
                                                        showCompleteDialog = true
                                                    },
                                                    onEditClick = { },
                                                    onCancelClick = { },
                                                    onUncancelClick = { }
                                                )
                                            }
                                        }
                                    }
                                }
                            }
                        }
                        }
                    }
                }

                else -> {}
            }
        }
    }

    if (showCompleteDialog && selectedTask != null) {
        CompleteTaskDialog(
            taskId = selectedTask!!.id,
            taskTitle = selectedTask!!.title,
            onDismiss = {
                showCompleteDialog = false
                selectedTask = null
                taskCompletionViewModel.resetCreateState()
            },
            onComplete = { request, images ->
                if (images.isNotEmpty()) {
                    taskCompletionViewModel.createTaskCompletionWithImages(
                        request = request,
                        images = images
                    )
                } else {
                    taskCompletionViewModel.createTaskCompletion(request)
                }
            }
        )
    }

    // Show error dialog when network call fails
    if (showErrorDialog) {
        ErrorDialog(
            message = errorMessage,
            onRetry = {
                showErrorDialog = false
                viewModel.loadTasks()
            },
            onDismiss = {
                showErrorDialog = false
            }
        )
    }
}
