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.material3.*
import androidx.compose.material3.pulltorefresh.PullToRefreshBox
import androidx.compose.runtime.*
import androidx.compose.ui.Modifier
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.unit.dp
import androidx.lifecycle.viewmodel.compose.viewModel
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import androidx.compose.ui.platform.testTag
import com.tt.honeyDue.testing.AccessibilityIds
import com.tt.honeyDue.ui.components.AddNewTaskWithResidenceDialog
import com.tt.honeyDue.ui.components.ApiResultHandler
import com.tt.honeyDue.ui.components.CompleteTaskDialog
import com.tt.honeyDue.ui.components.HandleErrors
import com.tt.honeyDue.ui.components.task.TaskCard
import com.tt.honeyDue.ui.components.task.DynamicTaskKanbanView
import com.tt.honeyDue.viewmodel.ResidenceViewModel
import com.tt.honeyDue.viewmodel.TaskCompletionViewModel
import com.tt.honeyDue.viewmodel.TaskViewModel
import com.tt.honeyDue.models.TaskDetail
import com.tt.honeyDue.network.ApiResult
import com.tt.honeyDue.ui.theme.*

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun AllTasksScreen(
    onNavigateToEditTask: (TaskDetail) -> Unit,
    onAddTask: () -> Unit = {},
    viewModel: TaskViewModel = viewModel { TaskViewModel() },
    taskCompletionViewModel: TaskCompletionViewModel = viewModel { TaskCompletionViewModel() },
    residenceViewModel: ResidenceViewModel = viewModel { ResidenceViewModel() },
    bottomNavBarPadding: androidx.compose.ui.unit.Dp = 0.dp,
    navigateToTaskId: Int? = null,
    onClearNavigateToTask: () -> Unit = {},
    onNavigateToCompleteTask: ((TaskDetail, String) -> Unit)? = null
) {
    val tasksState by viewModel.tasksState.collectAsStateWithLifecycle()
    val completionState by taskCompletionViewModel.createCompletionState.collectAsStateWithLifecycle()
    val myResidencesState by residenceViewModel.myResidencesState.collectAsStateWithLifecycle()
    val createTaskState by viewModel.taskAddNewCustomTaskState.collectAsStateWithLifecycle()

    var showCompleteDialog by remember { mutableStateOf(false) }
    var showNewTaskDialog by remember { mutableStateOf(false) }
    var selectedTask by remember { mutableStateOf<TaskDetail?>(null) }
    var isRefreshing by remember { mutableStateOf(false) }

    // Track which column to scroll to (from push notification navigation)
    var scrollToColumnIndex by remember { mutableStateOf<Int?>(null) }

    LaunchedEffect(Unit) {
        viewModel.loadTasks()
        residenceViewModel.loadMyResidences()
    }

    // Reset pull-to-refresh state once tasks finish loading
    LaunchedEffect(tasksState) {
        if (tasksState !is ApiResult.Loading) {
            isRefreshing = false
        }
    }

    // When tasks load and we have a pending navigation, find the column containing the task
    LaunchedEffect(navigateToTaskId, tasksState) {
        if (navigateToTaskId != null && tasksState is ApiResult.Success) {
            val taskData = (tasksState as ApiResult.Success).data
            // Find which column contains the task
            taskData.columns.forEachIndexed { index, column ->
                if (column.tasks.any { it.id == navigateToTaskId }) {
                    println("📬 Found task $navigateToTaskId in column $index '${column.name}'")
                    scrollToColumnIndex = index
                    return@LaunchedEffect
                }
            }
            // Task not found in any column
            println("📬 Task $navigateToTaskId not found in any column")
            onClearNavigateToTask()
        }
    }

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

    // Handle task creation success
    // Handle errors for task creation
    createTaskState.HandleErrors(
        onRetry = { /* Retry handled in dialog */ },
        errorTitle = "Failed to Create Task"
    )

    LaunchedEffect(createTaskState) {
        println("AllTasksScreen: createTaskState changed to $createTaskState")
        when (createTaskState) {
            is ApiResult.Success -> {
                println("AllTasksScreen: Task created successfully, closing dialog and reloading tasks")
                showNewTaskDialog = false
                viewModel.resetAddTaskState()
                viewModel.loadTasks()
            }
            else -> {}
        }
    }

    WarmGradientBackground {
        Scaffold(
            containerColor = androidx.compose.ui.graphics.Color.Transparent,
            topBar = {
                TopAppBar(
                    title = {
                        Text(
                            "All Tasks",
                            fontWeight = FontWeight.Bold
                        )
                    },
                    actions = {
                        IconButton(
                            onClick = { viewModel.loadTasks(forceRefresh = true) },
                            modifier = Modifier.testTag(AccessibilityIds.Task.refreshButton)
                        ) {
                            Icon(
                                Icons.Default.Refresh,
                                contentDescription = "Refresh"
                            )
                        }
                        IconButton(
                            onClick = { showNewTaskDialog = true },
                            enabled = myResidencesState is ApiResult.Success &&
                                (myResidencesState as ApiResult.Success).data.residences.isNotEmpty(),
                            modifier = Modifier.testTag(AccessibilityIds.Task.addButton)
                        ) {
                            Icon(
                                Icons.Default.Add,
                                contentDescription = "Add Task"
                            )
                        }
                    },
                    colors = TopAppBarDefaults.topAppBarColors(
                        containerColor = androidx.compose.ui.graphics.Color.Transparent
                    )
                )
            }
        ) { paddingValues ->
            ApiResultHandler(
                state = tasksState,
                onRetry = { viewModel.loadTasks(forceRefresh = true) },
                modifier = Modifier.padding(paddingValues),
                errorTitle = "Failed to Load Tasks"
            ) { taskData ->
                    val hasNoTasks = taskData.columns.all { it.tasks.isEmpty() }

                    if (hasNoTasks) {
                        Box(
                            modifier = Modifier
                                .fillMaxSize(),
                            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(
                                    "No tasks yet",
                                    style = MaterialTheme.typography.headlineSmall,
                                    fontWeight = FontWeight.SemiBold,
                                    color = MaterialTheme.colorScheme.textPrimary
                                )
                                Text(
                                    "Create your first task to get started",
                                    style = MaterialTheme.typography.bodyLarge,
                                    color = MaterialTheme.colorScheme.textSecondary
                                )
                                Spacer(modifier = Modifier.height(OrganicSpacing.compact))
                                OrganicPrimaryButton(
                                    text = "Add Task",
                                    onClick = { showNewTaskDialog = true },
                                    modifier = Modifier
                                        .fillMaxWidth(0.7f)
                                        .testTag(AccessibilityIds.Task.emptyStateView),
                                    enabled = myResidencesState is ApiResult.Success &&
                                        (myResidencesState as ApiResult.Success).data.residences.isNotEmpty()
                                )
                                if (myResidencesState is ApiResult.Success &&
                                    (myResidencesState as ApiResult.Success).data.residences.isEmpty()) {
                                    Text(
                                        "Add a property first from the Residences tab",
                                        style = MaterialTheme.typography.bodySmall,
                                        color = MaterialTheme.colorScheme.error
                                    )
                                }
                            }
                        }
                    } else {
                        PullToRefreshBox(
                            isRefreshing = isRefreshing,
                            onRefresh = {
                                isRefreshing = true
                                viewModel.loadTasks(forceRefresh = true)
                            },
                            modifier = Modifier.fillMaxSize()
                        ) {
                            DynamicTaskKanbanView(
                                columns = taskData.columns,
                                onCompleteTask = { task ->
                                    if (onNavigateToCompleteTask != null) {
                                        // Use full-screen navigation
                                        val residenceName = (myResidencesState as? ApiResult.Success)
                                            ?.data?.residences?.find { it.id == task.residenceId }?.name ?: ""
                                        onNavigateToCompleteTask(task, residenceName)
                                    } else {
                                        // Fall back to dialog
                                        selectedTask = task
                                        showCompleteDialog = true
                                    }
                                },
                                onEditTask = { task ->
                                    onNavigateToEditTask(task)
                                },
                                onCancelTask = { task ->
//                                viewModel.cancelTask(task.id) { _ ->
//                                    viewModel.loadTasks()
//                                }
                                },
                                onUncancelTask = { task ->
//                                viewModel.uncancelTask(task.id) { _ ->
//                                    viewModel.loadTasks()
//                                }
                                },
                                onMarkInProgress = { task ->
                                    viewModel.markInProgress(task.id) { success ->
                                        if (success) {
                                            viewModel.loadTasks()
                                        }
                                    }
                                },
                                onArchiveTask = { task ->
                                    viewModel.archiveTask(task.id) { success ->
                                        if (success) {
                                            viewModel.loadTasks()
                                        }
                                    }
                                },
                                onUnarchiveTask = { task ->
                                    viewModel.unarchiveTask(task.id) { success ->
                                        if (success) {
                                            viewModel.loadTasks()
                                        }
                                    }
                                },
                                modifier = Modifier,
                                bottomPadding = bottomNavBarPadding,
                                scrollToColumnIndex = scrollToColumnIndex,
                                onScrollComplete = {
                                    scrollToColumnIndex = null
                                    onClearNavigateToTask()
                                }
                            )
                        }
                    }
                }
            }
        }

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

    if (showNewTaskDialog && myResidencesState is ApiResult.Success) {
        AddNewTaskWithResidenceDialog(
            residencesResponse = (myResidencesState as ApiResult.Success).data,
            onDismiss = {
                showNewTaskDialog = false
                viewModel.resetAddTaskState()
            },
            onCreate = { taskRequest ->
                println("AllTasksScreen: onCreate called with request: $taskRequest")
                viewModel.createNewTask(taskRequest)
            },
            isLoading = createTaskState is ApiResult.Loading,
            errorMessage = if (createTaskState is ApiResult.Error) {
                com.tt.honeyDue.util.ErrorMessageParser.parse((createTaskState as ApiResult.Error).message)
            } else null
        )
    }
}
