package com.tt.honeyDue.ui.components

import androidx.compose.foundation.layout.*
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.foundation.verticalScroll
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.testTag
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.unit.dp
import com.tt.honeyDue.data.DataManager
import com.tt.honeyDue.testing.AccessibilityIds
import com.tt.honeyDue.models.TaskTemplate
import com.tt.honeyDue.repository.LookupsRepository
import com.tt.honeyDue.models.MyResidencesResponse
import com.tt.honeyDue.models.TaskCategory
import com.tt.honeyDue.models.TaskCreateRequest
import com.tt.honeyDue.models.TaskFrequency
import com.tt.honeyDue.models.TaskPriority
import com.tt.honeyDue.analytics.PostHogAnalytics
import com.tt.honeyDue.analytics.AnalyticsEvents
import honeydue.composeapp.generated.resources.*
import org.jetbrains.compose.resources.stringResource

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun AddTaskDialog(
    residenceId: Int? = null,
    residencesResponse: MyResidencesResponse? = null,
    onDismiss: () -> Unit,
    onCreate: (TaskCreateRequest) -> Unit,
    isLoading: Boolean = false,
    errorMessage: String? = null
) {
    // Determine if we need residence selection
    val needsResidenceSelection = residenceId == null

    var title by remember { mutableStateOf("") }
    var description by remember { mutableStateOf("") }
    var intervalDays by remember { mutableStateOf("") }
    var dueDate by remember { mutableStateOf("") }
    var estimatedCost by remember { mutableStateOf("") }

    var selectedResidenceId by remember {
        mutableStateOf(
            residenceId ?: residencesResponse?.residences?.firstOrNull()?.id ?: 0
        )
    }
    var category by remember { mutableStateOf(TaskCategory(id = 0, name = "")) }
    var frequency by remember { mutableStateOf(TaskFrequency(id = 0, name = "")) }
    var priority by remember { mutableStateOf(TaskPriority(id = 0, name = "")) }

    var showResidenceDropdown by remember { mutableStateOf(false) }
    var showFrequencyDropdown by remember { mutableStateOf(false) }
    var showPriorityDropdown by remember { mutableStateOf(false) }
    var showCategoryDropdown by remember { mutableStateOf(false) }

    var titleError by remember { mutableStateOf(false) }
    var categoryError by remember { mutableStateOf(false) }
    var dueDateError by remember { mutableStateOf(false) }
    var residenceError by remember { mutableStateOf(false) }

    // Template suggestions state (inline search only — full-screen browse
    // lives in TaskTemplatesBrowserScreen).
    var showSuggestions by remember { mutableStateOf(false) }

    // Get data from LookupsRepository and DataManager
    val frequencies by LookupsRepository.taskFrequencies.collectAsState()
    val priorities by LookupsRepository.taskPriorities.collectAsState()
    val categories by LookupsRepository.taskCategories.collectAsState()
    val allTemplates by DataManager.taskTemplates.collectAsState()

    // Search templates locally
    val filteredSuggestions = remember(title, allTemplates) {
        if (title.length >= 2) {
            DataManager.searchTaskTemplates(title)
        } else {
            emptyList()
        }
    }

    // Helper function to apply a task template
    fun selectTaskTemplate(template: TaskTemplate) {
        title = template.title
        description = template.description

        // Auto-select matching category by ID or name
        template.categoryId?.let { catId ->
            categories.find { it.id == catId }?.let {
                category = it
            }
        } ?: template.category?.let { cat ->
            categories.find { it.name.equals(cat.name, ignoreCase = true) }?.let {
                category = it
            }
        }

        // Auto-select matching frequency by ID or name
        template.frequencyId?.let { freqId ->
            frequencies.find { it.id == freqId }?.let {
                frequency = it
            }
        } ?: template.frequency?.let { freq ->
            frequencies.find { it.name.equals(freq.name, ignoreCase = true) }?.let {
                frequency = it
            }
        }

        showSuggestions = false
    }

    // Track screen view
    LaunchedEffect(Unit) {
        PostHogAnalytics.screen(AnalyticsEvents.NEW_TASK_SCREEN_SHOWN)
    }

    // Set defaults when data loads
    LaunchedEffect(frequencies) {
        if (frequencies.isNotEmpty()) {
            frequency = frequencies.first()
        }
    }

    LaunchedEffect(priorities) {
        if (priorities.isNotEmpty()) {
            priority = priorities.first()
        }
    }

    AlertDialog(
        onDismissRequest = onDismiss,
        title = { Text(stringResource(Res.string.tasks_add_new)) },
        text = {
            Column(
                modifier = Modifier
                    .fillMaxWidth()
                    .verticalScroll(rememberScrollState()),
                verticalArrangement = Arrangement.spacedBy(12.dp)
            ) {
                // Residence Selector (only if residenceId is null)
                if (needsResidenceSelection && residencesResponse != null) {
                    ExposedDropdownMenuBox(
                        expanded = showResidenceDropdown,
                        onExpandedChange = { showResidenceDropdown = it }
                    ) {
                        OutlinedTextField(
                            value = residencesResponse.residences.find { it.id == selectedResidenceId }?.name ?: "",
                            onValueChange = { },
                            label = { Text(stringResource(Res.string.tasks_property_required)) },
                            modifier = Modifier
                                .fillMaxWidth()
                                .menuAnchor()
                                .testTag(AccessibilityIds.Task.residencePicker),
                            isError = residenceError,
                            supportingText = if (residenceError) {
                                { Text(stringResource(Res.string.tasks_property_error)) }
                            } else null,
                            trailingIcon = { ExposedDropdownMenuDefaults.TrailingIcon(expanded = showResidenceDropdown) },
                            readOnly = true,
                            enabled = residencesResponse.residences.isNotEmpty()
                        )
                        ExposedDropdownMenu(
                            expanded = showResidenceDropdown,
                            onDismissRequest = { showResidenceDropdown = false }
                        ) {
                            residencesResponse.residences.forEach { residence ->
                                DropdownMenuItem(
                                    text = { Text(residence.name) },
                                    onClick = {
                                        selectedResidenceId = residence.id
                                        residenceError = false
                                        showResidenceDropdown = false
                                    }
                                )
                            }
                        }
                    }
                }

                // Note: full-screen template browsing (multi-select + bulk
                // create) now lives in TaskTemplatesBrowserScreen; this
                // dialog keeps only inline suggestions while typing the title.

                // Title with inline suggestions
                Column {
                    OutlinedTextField(
                        value = title,
                        onValueChange = {
                            title = it
                            titleError = false
                            showSuggestions = it.length >= 2 && filteredSuggestions.isNotEmpty()
                        },
                        label = { Text(stringResource(Res.string.tasks_title_required)) },
                        modifier = Modifier
                            .fillMaxWidth()
                            .testTag(AccessibilityIds.Task.titleField),
                        isError = titleError,
                        supportingText = if (titleError) {
                            { Text(stringResource(Res.string.tasks_title_error)) }
                        } else null,
                        singleLine = true
                    )

                    // Inline suggestions dropdown
                    if (showSuggestions && filteredSuggestions.isNotEmpty()) {
                        TaskSuggestionDropdown(
                            suggestions = filteredSuggestions,
                            onSelect = { template ->
                                selectTaskTemplate(template)
                            },
                            modifier = Modifier.fillMaxWidth()
                        )
                    }
                }

                // Description
                OutlinedTextField(
                    value = description,
                    onValueChange = { description = it },
                    label = { Text(stringResource(Res.string.tasks_description_label)) },
                    modifier = Modifier
                        .fillMaxWidth()
                        .testTag(AccessibilityIds.Task.descriptionField),
                    minLines = 2,
                    maxLines = 4
                )

                // Category
                ExposedDropdownMenuBox(
                    expanded = showCategoryDropdown,
                    onExpandedChange = { showCategoryDropdown = it }
                ) {
                    OutlinedTextField(
                        value = categories.find { it == category }?.name ?: "",
                        onValueChange = { },
                        label = { Text(stringResource(Res.string.tasks_category_required)) },
                        modifier = Modifier
                            .fillMaxWidth()
                            .menuAnchor()
                            .testTag(AccessibilityIds.Task.categoryPicker),
                        isError = categoryError,
                        supportingText = if (categoryError) {
                            { Text(stringResource(Res.string.tasks_category_error)) }
                        } else null,
                        trailingIcon = { ExposedDropdownMenuDefaults.TrailingIcon(expanded = showCategoryDropdown) },
                        readOnly = false,
                        enabled = categories.isNotEmpty()
                    )
                    ExposedDropdownMenu(
                        expanded = showCategoryDropdown,
                        onDismissRequest = { showCategoryDropdown = false }
                    ) {
                        categories.forEach { cat ->
                            DropdownMenuItem(
                                text = { Text(cat.name) },
                                onClick = {
                                    category = cat
                                    categoryError = false
                                    showCategoryDropdown = false
                                }
                            )
                        }
                    }
                }

                // Frequency
                ExposedDropdownMenuBox(
                    expanded = showFrequencyDropdown,
                    onExpandedChange = { showFrequencyDropdown = it }
                ) {
                    OutlinedTextField(
                        value = frequencies.find { it == frequency }?.displayName ?: "",
                        onValueChange = { },
                        label = { Text(stringResource(Res.string.tasks_frequency_label)) },
                        modifier = Modifier
                            .fillMaxWidth()
                            .menuAnchor()
                            .testTag(AccessibilityIds.Task.frequencyPicker),
                        readOnly = true,
                        trailingIcon = { ExposedDropdownMenuDefaults.TrailingIcon(expanded = showFrequencyDropdown) },
                        enabled = frequencies.isNotEmpty()
                    )
                    ExposedDropdownMenu(
                        expanded = showFrequencyDropdown,
                        onDismissRequest = { showFrequencyDropdown = false }
                    ) {
                        frequencies.forEach { freq ->
                            DropdownMenuItem(
                                text = { Text(freq.displayName) },
                                onClick = {
                                    frequency = freq
                                    showFrequencyDropdown = false
                                    // Clear interval days if frequency is not "Custom"
                                    if (!freq.name.equals("Custom", ignoreCase = true)) {
                                        intervalDays = ""
                                    }
                                }
                            )
                        }
                    }
                }

                // Custom Interval Days (only for "Custom" frequency)
                if (frequency.name.equals("Custom", ignoreCase = true)) {
                    OutlinedTextField(
                        value = intervalDays,
                        onValueChange = { intervalDays = it.filter { char -> char.isDigit() } },
                        label = { Text(stringResource(Res.string.tasks_interval_days)) },
                        modifier = Modifier
                            .fillMaxWidth()
                            .testTag(AccessibilityIds.Task.intervalDaysField),
                        keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number),
                        supportingText = { Text(stringResource(Res.string.tasks_custom_interval_help)) },
                        singleLine = true
                    )
                }

                // Due Date
                OutlinedTextField(
                    value = dueDate,
                    onValueChange = {
                        dueDate = it
                        dueDateError = false
                    },
                    label = { Text(stringResource(Res.string.tasks_due_date_required)) },
                    modifier = Modifier
                        .fillMaxWidth()
                        .testTag(AccessibilityIds.Task.dueDatePicker),
                    isError = dueDateError,
                    supportingText = if (dueDateError) {
                        { Text(stringResource(Res.string.tasks_due_date_format_error)) }
                    } else {
                        { Text(stringResource(Res.string.tasks_due_date_format)) }
                    },
                    singleLine = true
                )

                // Priority
                ExposedDropdownMenuBox(
                    expanded = showPriorityDropdown,
                    onExpandedChange = { showPriorityDropdown = it }
                ) {
                    OutlinedTextField(
                        value = priorities.find { it.name == priority.name }?.displayName ?: "",
                        onValueChange = { },
                        label = { Text(stringResource(Res.string.tasks_priority_label)) },
                        modifier = Modifier
                            .fillMaxWidth()
                            .menuAnchor()
                            .testTag(AccessibilityIds.Task.priorityPicker),
                        readOnly = true,
                        trailingIcon = { ExposedDropdownMenuDefaults.TrailingIcon(expanded = showPriorityDropdown) },
                        enabled = priorities.isNotEmpty()
                    )
                    ExposedDropdownMenu(
                        expanded = showPriorityDropdown,
                        onDismissRequest = { showPriorityDropdown = false }
                    ) {
                        priorities.forEach { prio ->
                            DropdownMenuItem(
                                text = { Text(prio.displayName) },
                                onClick = {
                                    priority = prio
                                    showPriorityDropdown = false
                                }
                            )
                        }
                    }
                }

                // Estimated Cost
                OutlinedTextField(
                    value = estimatedCost,
                    onValueChange = { estimatedCost = it },
                    label = { Text(stringResource(Res.string.tasks_estimated_cost_label)) },
                    modifier = Modifier
                        .fillMaxWidth()
                        .testTag(AccessibilityIds.Task.estimatedCostField),
                    keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Decimal),
                    prefix = { Text("$") },
                    singleLine = true
                )

                // Error message display
                if (errorMessage != null) {
                    Text(
                        text = errorMessage,
                        color = MaterialTheme.colorScheme.error,
                        style = MaterialTheme.typography.bodySmall,
                        modifier = Modifier.padding(top = 8.dp)
                    )
                }
            }
        },
        confirmButton = {
            Button(
                modifier = Modifier.testTag(AccessibilityIds.Task.saveButton),
                onClick = {
                    // Validation
                    var hasError = false

                    if (needsResidenceSelection && selectedResidenceId == 0) {
                        residenceError = true
                        hasError = true
                    }

                    if (title.isBlank()) {
                        titleError = true
                        hasError = true
                    }

                    if (dueDate.isBlank() || !isValidDateFormat(dueDate)) {
                        dueDateError = true
                        hasError = true
                    }

                    if (!hasError) {
                        onCreate(
                            TaskCreateRequest(
                                residenceId = selectedResidenceId,
                                title = title,
                                description = description.ifBlank { null },
                                categoryId = if (category.id > 0) category.id else null,
                                frequencyId = if (frequency.id > 0) frequency.id else null,
                                customIntervalDays = if (frequency.name.equals("Custom", ignoreCase = true) && intervalDays.isNotBlank()) {
                                    intervalDays.toIntOrNull()
                                } else null,
                                priorityId = if (priority.id > 0) priority.id else null,
                                inProgress = false,
                                dueDate = dueDate,
                                estimatedCost = estimatedCost.ifBlank { null }?.toDoubleOrNull()
                            )
                        )
                    }
                },
                enabled = !isLoading
            ) {
                if (isLoading) {
                    CircularProgressIndicator(
                        modifier = Modifier.size(20.dp),
                        strokeWidth = 2.dp,
                        color = MaterialTheme.colorScheme.onPrimary
                    )
                } else {
                    Text(stringResource(Res.string.tasks_create))
                }
            }
        },
        dismissButton = {
            TextButton(
                modifier = Modifier.testTag(AccessibilityIds.Task.formCancelButton),
                onClick = onDismiss
            ) {
                Text(stringResource(Res.string.common_cancel))
            }
        }
    )
}

// Helper function to validate date format
private fun isValidDateFormat(date: String): Boolean {
    val datePattern = Regex("^\\d{4}-\\d{2}-\\d{2}$")
    return datePattern.matches(date)
}
