package com.tt.honeyDue.ui.screens.task

import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.ExperimentalLayoutApi
import androidx.compose.foundation.layout.FlowRow
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.imePadding
import androidx.compose.foundation.layout.padding
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.material.icons.filled.Save
import androidx.compose.material3.Button
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.CircularProgressIndicator
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.FilterChip
import androidx.compose.material3.FilterChipDefaults
import androidx.compose.material3.Icon
import androidx.compose.material3.IconButton
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBar
import androidx.compose.material3.TopAppBarDefaults
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.ui.Modifier
import androidx.compose.ui.platform.testTag
import androidx.compose.ui.text.font.FontWeight
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.network.ApiResult
import com.tt.honeyDue.repository.LookupsRepository
import com.tt.honeyDue.testing.AccessibilityIds
import com.tt.honeyDue.ui.components.common.StandardCard
import com.tt.honeyDue.ui.components.forms.FormTextField
import com.tt.honeyDue.ui.theme.AppRadius
import com.tt.honeyDue.ui.theme.AppSpacing
import com.tt.honeyDue.util.ErrorMessageParser

/**
 * Android port of iOS AddTaskWithResidenceView (P2 Stream I).
 *
 * The residence is pre-selected via [residenceId] so the user doesn't pick
 * a property here — callers enter this screen from a residence context
 * (e.g. "Add Task" inside a residence detail screen).
 *
 * On submit, calls [APILayer.createTask] via the ViewModel with the
 * residenceId baked into the request. On success, [onCreated] fires so the
 * caller can pop + refresh the parent task list. On error, an inline
 * message is shown and the user stays on the form.
 */
@OptIn(ExperimentalMaterial3Api::class, ExperimentalLayoutApi::class)
@Composable
fun AddTaskWithResidenceScreen(
    residenceId: Int,
    onNavigateBack: () -> Unit,
    onCreated: () -> Unit,
    viewModel: AddTaskWithResidenceViewModel = viewModel {
        AddTaskWithResidenceViewModel(residenceId = residenceId)
    }
) {
    val title by viewModel.title.collectAsStateWithLifecycle()
    val description by viewModel.description.collectAsStateWithLifecycle()
    val priorityId by viewModel.priorityId.collectAsStateWithLifecycle()
    val categoryId by viewModel.categoryId.collectAsStateWithLifecycle()
    val frequencyId by viewModel.frequencyId.collectAsStateWithLifecycle()
    val dueDate by viewModel.dueDate.collectAsStateWithLifecycle()
    val estimatedCost by viewModel.estimatedCost.collectAsStateWithLifecycle()
    val titleError by viewModel.titleError.collectAsStateWithLifecycle()
    val canSubmit by viewModel.canSubmit.collectAsStateWithLifecycle()
    val submitState by viewModel.submitState.collectAsStateWithLifecycle()

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

    val isSubmitting = submitState is ApiResult.Loading

    Scaffold(
        topBar = {
            TopAppBar(
                title = { Text("New Task", fontWeight = FontWeight.SemiBold) },
                navigationIcon = {
                    IconButton(
                        onClick = onNavigateBack,
                        modifier = Modifier.testTag(AccessibilityIds.Task.formCancelButton)
                    ) {
                        Icon(Icons.AutoMirrored.Filled.ArrowBack, contentDescription = "Back")
                    }
                },
                colors = TopAppBarDefaults.topAppBarColors(
                    containerColor = MaterialTheme.colorScheme.surface
                )
            )
        }
    ) { paddingValues ->
        Column(
            modifier = Modifier
                .fillMaxSize()
                .padding(paddingValues)
                .imePadding()
                .verticalScroll(rememberScrollState())
                .padding(horizontal = AppSpacing.lg, vertical = AppSpacing.md),
            verticalArrangement = Arrangement.spacedBy(AppSpacing.md)
        ) {
            StandardCard(modifier = Modifier.fillMaxWidth()) {
                FormTextField(
                    value = title,
                    onValueChange = viewModel::onTitleChange,
                    label = "Title",
                    modifier = Modifier.testTag(AccessibilityIds.Task.titleField),
                    placeholder = "e.g. Flush water heater",
                    error = titleError,
                    enabled = !isSubmitting
                )
            }

            StandardCard(modifier = Modifier.fillMaxWidth()) {
                FormTextField(
                    value = description,
                    onValueChange = viewModel::onDescriptionChange,
                    label = "Description",
                    modifier = Modifier.testTag(AccessibilityIds.Task.descriptionField),
                    placeholder = "Optional details",
                    singleLine = false,
                    maxLines = 4,
                    enabled = !isSubmitting
                )
            }

            // Priority chips
            StandardCard(modifier = Modifier.fillMaxWidth()) {
                Text(
                    text = "Priority",
                    style = MaterialTheme.typography.titleSmall,
                    fontWeight = FontWeight.SemiBold,
                    color = MaterialTheme.colorScheme.onSurface
                )
                FlowRow(
                    horizontalArrangement = Arrangement.spacedBy(AppSpacing.sm),
                    verticalArrangement = Arrangement.spacedBy(AppSpacing.sm),
                    modifier = Modifier.padding(top = AppSpacing.sm)
                ) {
                    priorities.forEach { p ->
                        FilterChip(
                            selected = priorityId == p.id,
                            onClick = { viewModel.onPriorityIdChange(p.id) },
                            label = { Text(p.displayName) },
                            enabled = !isSubmitting,
                            colors = FilterChipDefaults.filterChipColors()
                        )
                    }
                }
            }

            // Category chips
            StandardCard(modifier = Modifier.fillMaxWidth()) {
                Text(
                    text = "Category",
                    style = MaterialTheme.typography.titleSmall,
                    fontWeight = FontWeight.SemiBold,
                    color = MaterialTheme.colorScheme.onSurface
                )
                FlowRow(
                    horizontalArrangement = Arrangement.spacedBy(AppSpacing.sm),
                    verticalArrangement = Arrangement.spacedBy(AppSpacing.sm),
                    modifier = Modifier.padding(top = AppSpacing.sm)
                ) {
                    categories.forEach { c ->
                        FilterChip(
                            selected = categoryId == c.id,
                            onClick = { viewModel.onCategoryIdChange(c.id) },
                            label = { Text(c.name) },
                            enabled = !isSubmitting
                        )
                    }
                }
            }

            // Frequency chips
            StandardCard(modifier = Modifier.fillMaxWidth()) {
                Text(
                    text = "Frequency",
                    style = MaterialTheme.typography.titleSmall,
                    fontWeight = FontWeight.SemiBold,
                    color = MaterialTheme.colorScheme.onSurface
                )
                FlowRow(
                    horizontalArrangement = Arrangement.spacedBy(AppSpacing.sm),
                    verticalArrangement = Arrangement.spacedBy(AppSpacing.sm),
                    modifier = Modifier.padding(top = AppSpacing.sm)
                ) {
                    frequencies.forEach { f ->
                        FilterChip(
                            selected = frequencyId == f.id,
                            onClick = { viewModel.onFrequencyIdChange(f.id) },
                            label = { Text(f.displayName) },
                            enabled = !isSubmitting
                        )
                    }
                }
            }

            // Due date (optional, yyyy-MM-dd string matches Go API)
            StandardCard(modifier = Modifier.fillMaxWidth()) {
                FormTextField(
                    value = dueDate,
                    onValueChange = viewModel::onDueDateChange,
                    label = "Due date (optional)",
                    placeholder = "yyyy-MM-dd",
                    enabled = !isSubmitting,
                    helperText = "Leave blank for no due date"
                )
            }

            // Estimated cost (optional)
            StandardCard(modifier = Modifier.fillMaxWidth()) {
                FormTextField(
                    value = estimatedCost,
                    onValueChange = viewModel::onEstimatedCostChange,
                    label = "Estimated cost (optional)",
                    placeholder = "0.00",
                    keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Decimal),
                    enabled = !isSubmitting
                )
            }

            // Inline error (not a navigation pop)
            (submitState as? ApiResult.Error)?.let { err ->
                Text(
                    text = ErrorMessageParser.parse(err.message),
                    style = MaterialTheme.typography.bodyMedium,
                    color = MaterialTheme.colorScheme.error,
                    modifier = Modifier.padding(horizontal = AppSpacing.sm)
                )
            }

            Button(
                onClick = { viewModel.submit(onSuccess = onCreated) },
                enabled = canSubmit && !isSubmitting,
                modifier = Modifier
                    .fillMaxWidth()
                    .height(52.dp)
                    .testTag(AccessibilityIds.Task.saveButton),
                shape = androidx.compose.foundation.shape.RoundedCornerShape(AppRadius.md),
                colors = ButtonDefaults.buttonColors(
                    containerColor = MaterialTheme.colorScheme.primary
                )
            ) {
                if (isSubmitting) {
                    CircularProgressIndicator(
                        modifier = Modifier.height(20.dp),
                        strokeWidth = 2.dp,
                        color = MaterialTheme.colorScheme.onPrimary
                    )
                } else {
                    Icon(Icons.Default.Save, contentDescription = null) // decorative
                    Text(
                        text = "Create Task",
                        modifier = Modifier.padding(start = AppSpacing.sm),
                        fontWeight = FontWeight.SemiBold
                    )
                }
            }
        }
    }
}
