package com.tt.honeyDue.ui.screens

import androidx.compose.foundation.layout.*
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.automirrored.filled.ArrowBack
import androidx.compose.material3.*
import androidx.compose.runtime.*
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 androidx.lifecycle.viewmodel.compose.viewModel
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import com.tt.honeyDue.testing.AccessibilityIds
import com.tt.honeyDue.ui.components.HandleErrors
import com.tt.honeyDue.viewmodel.ResidenceViewModel
import com.tt.honeyDue.repository.LookupsRepository
import com.tt.honeyDue.models.*
import com.tt.honeyDue.network.ApiResult
import com.tt.honeyDue.ui.theme.*
import honeydue.composeapp.generated.resources.*
import org.jetbrains.compose.resources.stringResource

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun EditTaskScreen(
    task: TaskDetail,
    onNavigateBack: () -> Unit,
    onTaskUpdated: () -> Unit,
    viewModel: ResidenceViewModel = viewModel { ResidenceViewModel() }
) {
    var title by remember { mutableStateOf(task.title) }
    var description by remember { mutableStateOf(task.description ?: "") }
    var selectedCategory by remember { mutableStateOf<TaskCategory?>(task.category) }
    var selectedFrequency by remember { mutableStateOf<TaskFrequency?>(task.frequency) }
    var selectedPriority by remember { mutableStateOf<TaskPriority?>(task.priority) }
    var inProgress by remember { mutableStateOf(task.inProgress) }
    var dueDate by remember { mutableStateOf(task.dueDate ?: "") }
    var estimatedCost by remember { mutableStateOf(task.estimatedCost?.toString() ?: "") }
    var customIntervalDays by remember { mutableStateOf(task.customIntervalDays?.toString() ?: "") }

    var categoryExpanded by remember { mutableStateOf(false) }
    var frequencyExpanded by remember { mutableStateOf(false) }
    var priorityExpanded by remember { mutableStateOf(false) }

    val updateTaskState by viewModel.updateTaskState.collectAsStateWithLifecycle()
    val categories by LookupsRepository.taskCategories.collectAsStateWithLifecycle()
    val frequencies by LookupsRepository.taskFrequencies.collectAsStateWithLifecycle()
    val priorities by LookupsRepository.taskPriorities.collectAsStateWithLifecycle()

    // Validation errors
    var titleError by remember { mutableStateOf("") }
    var dueDateError by remember { mutableStateOf("") }

    // Handle errors for task update
    updateTaskState.HandleErrors(
        onRetry = { /* Retry handled in UI */ },
        errorTitle = stringResource(Res.string.tasks_failed_to_update)
    )

    // Handle update state changes
    LaunchedEffect(updateTaskState) {
        when (updateTaskState) {
            is ApiResult.Success -> {
                viewModel.resetUpdateTaskState()
                onTaskUpdated()
            }
            else -> {}
        }
    }

    val titleRequiredError = stringResource(Res.string.tasks_title_error)
    val dueDateRequiredError = stringResource(Res.string.tasks_due_date_error)

    fun validateForm(): Boolean {
        var isValid = true

        if (title.isBlank()) {
            titleError = titleRequiredError
            isValid = false
        } else {
            titleError = ""
        }

        if (dueDate.isNullOrBlank()) {
            dueDateError = dueDateRequiredError
            isValid = false
        } else {
            dueDateError = ""
        }

        return isValid
    }

    Scaffold(
        topBar = {
            TopAppBar(
                title = { Text(stringResource(Res.string.tasks_edit_title)) },
                navigationIcon = {
                    IconButton(
                        onClick = onNavigateBack,
                        modifier = Modifier.testTag(AccessibilityIds.Task.formCancelButton)
                    ) {
                        Icon(Icons.AutoMirrored.Filled.ArrowBack, contentDescription = stringResource(Res.string.common_back))
                    }
                }
            )
        }
    ) { paddingValues ->
        WarmGradientBackground {
            Column(
                modifier = Modifier
                    .fillMaxSize()
                    .padding(paddingValues)
                    .imePadding()
                    .padding(OrganicSpacing.cozy)
                    .verticalScroll(rememberScrollState()),
                verticalArrangement = Arrangement.spacedBy(OrganicSpacing.cozy)
            ) {
                // Required fields section
                Text(
                    text = stringResource(Res.string.tasks_details),
                    style = MaterialTheme.typography.titleMedium,
                    color = MaterialTheme.colorScheme.primary
                )

                OutlinedTextField(
                    value = title,
                    onValueChange = { title = it },
                    label = { Text(stringResource(Res.string.tasks_title_required)) },
                    modifier = Modifier
                        .fillMaxWidth()
                        .testTag(AccessibilityIds.Task.titleField),
                    isError = titleError.isNotEmpty(),
                    supportingText = if (titleError.isNotEmpty()) {
                        { Text(titleError) }
                    } else null
                )

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

                // Category dropdown
                ExposedDropdownMenuBox(
                    expanded = categoryExpanded,
                    onExpandedChange = { categoryExpanded = it }
                ) {
                    OutlinedTextField(
                        value = selectedCategory?.name?.replaceFirstChar { it.uppercase() } ?: "",
                        onValueChange = {},
                        readOnly = true,
                        label = { Text(stringResource(Res.string.tasks_category_required)) },
                        trailingIcon = { ExposedDropdownMenuDefaults.TrailingIcon(expanded = categoryExpanded) },
                        modifier = Modifier
                            .fillMaxWidth()
                            .menuAnchor(),
                        enabled = categories.isNotEmpty()
                    )
                    ExposedDropdownMenu(
                        expanded = categoryExpanded,
                        onDismissRequest = { categoryExpanded = false }
                    ) {
                        categories.forEach { category ->
                            DropdownMenuItem(
                                text = { Text(category.name.replaceFirstChar { it.uppercase() }) },
                                onClick = {
                                    selectedCategory = category
                                    categoryExpanded = false
                                }
                            )
                        }
                    }
                }

                // Frequency dropdown
                ExposedDropdownMenuBox(
                    expanded = frequencyExpanded,
                    onExpandedChange = { frequencyExpanded = it }
                ) {
                    OutlinedTextField(
                        value = selectedFrequency?.name?.replaceFirstChar { it.uppercase() } ?: "",
                        onValueChange = {},
                        readOnly = true,
                        label = { Text(stringResource(Res.string.tasks_frequency_required)) },
                        trailingIcon = { ExposedDropdownMenuDefaults.TrailingIcon(expanded = frequencyExpanded) },
                        modifier = Modifier
                            .fillMaxWidth()
                            .menuAnchor(),
                        enabled = frequencies.isNotEmpty()
                    )
                    ExposedDropdownMenu(
                        expanded = frequencyExpanded,
                        onDismissRequest = { frequencyExpanded = false }
                    ) {
                        frequencies.forEach { frequency ->
                            DropdownMenuItem(
                                text = { Text(frequency.name.replaceFirstChar { it.uppercase() }) },
                                onClick = {
                                    selectedFrequency = frequency
                                    frequencyExpanded = false
                                    // Clear custom interval if not Custom frequency
                                    if (!frequency.name.equals("Custom", ignoreCase = true)) {
                                        customIntervalDays = ""
                                    }
                                }
                            )
                        }
                    }
                }

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

                // Priority dropdown
                ExposedDropdownMenuBox(
                    expanded = priorityExpanded,
                    onExpandedChange = { priorityExpanded = it }
                ) {
                    OutlinedTextField(
                        value = selectedPriority?.name?.replaceFirstChar { it.uppercase() } ?: "",
                        onValueChange = {},
                        readOnly = true,
                        label = { Text(stringResource(Res.string.tasks_priority_required)) },
                        trailingIcon = { ExposedDropdownMenuDefaults.TrailingIcon(expanded = priorityExpanded) },
                        modifier = Modifier
                            .fillMaxWidth()
                            .menuAnchor(),
                        enabled = priorities.isNotEmpty()
                    )
                    ExposedDropdownMenu(
                        expanded = priorityExpanded,
                        onDismissRequest = { priorityExpanded = false }
                    ) {
                        priorities.forEach { priority ->
                            DropdownMenuItem(
                                text = { Text(priority.name.replaceFirstChar { it.uppercase() }) },
                                onClick = {
                                    selectedPriority = priority
                                    priorityExpanded = false
                                }
                            )
                        }
                    }
                }

                // In Progress toggle
                Row(
                    modifier = Modifier.fillMaxWidth(),
                    horizontalArrangement = Arrangement.SpaceBetween,
                    verticalAlignment = androidx.compose.ui.Alignment.CenterVertically
                ) {
                    Text(
                        text = stringResource(Res.string.tasks_in_progress_label),
                        style = MaterialTheme.typography.bodyLarge
                    )
                    Switch(
                        checked = inProgress,
                        onCheckedChange = { inProgress = it }
                    )
                }

                OutlinedTextField(
                    value = dueDate,
                    onValueChange = { dueDate = it },
                    label = { Text(stringResource(Res.string.tasks_due_date_required)) },
                    modifier = Modifier.fillMaxWidth(),
                    isError = dueDateError.isNotEmpty(),
                    supportingText = if (dueDateError.isNotEmpty()) {
                        { Text(dueDateError) }
                    } else null,
                    placeholder = { Text(stringResource(Res.string.tasks_due_date_placeholder)) }
                )

                OutlinedTextField(
                    value = estimatedCost,
                    onValueChange = { estimatedCost = it },
                    label = { Text(stringResource(Res.string.tasks_estimated_cost_label)) },
                    keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Decimal),
                    modifier = Modifier.fillMaxWidth(),
                    prefix = { Text("$") }
                )

                // Error message
                if (updateTaskState is ApiResult.Error) {
                    Text(
                        text = com.tt.honeyDue.util.ErrorMessageParser.parse((updateTaskState as ApiResult.Error).message),
                        color = MaterialTheme.colorScheme.error,
                        style = MaterialTheme.typography.bodySmall
                    )
                }

                // Submit button
                OrganicPrimaryButton(
                    text = stringResource(Res.string.tasks_update),
                    modifier = Modifier.testTag(AccessibilityIds.Task.saveButton),
                    onClick = {
                        if (validateForm() && selectedCategory != null &&
                            selectedFrequency != null && selectedPriority != null) {
                            viewModel.updateTask(
                                taskId = task.id,
                                request = TaskCreateRequest(
                                    residenceId = task.residenceId,
                                    title = title,
                                    description = description.ifBlank { null },
                                    categoryId = selectedCategory!!.id,
                                    frequencyId = selectedFrequency!!.id,
                                    customIntervalDays = if (selectedFrequency?.name?.equals("Custom", ignoreCase = true) == true && customIntervalDays.isNotBlank()) {
                                        customIntervalDays.toIntOrNull()
                                    } else null,
                                    priorityId = selectedPriority!!.id,
                                    inProgress = inProgress,
                                    dueDate = dueDate,
                                    estimatedCost = estimatedCost.ifBlank { null }?.toDoubleOrNull()
                                )
                            )
                        }
                    },
                    enabled = validateForm() && selectedCategory != null &&
                             selectedFrequency != null && selectedPriority != null,
                    isLoading = updateTaskState is ApiResult.Loading
                )

                Spacer(modifier = Modifier.height(OrganicSpacing.cozy))
            }
        }
    }
}
