package com.tt.honeyDue.ui.screens

import androidx.compose.animation.animateColorAsState
import androidx.compose.animation.core.tween
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.clickable
import androidx.compose.foundation.horizontalScroll
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.*
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.layout.ContentScale
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.testing.AccessibilityIds
import honeydue.composeapp.generated.resources.*
import com.tt.honeyDue.models.TaskCompletionCreateRequest
import com.tt.honeyDue.models.ContractorSummary
import com.tt.honeyDue.network.ApiResult
import com.tt.honeyDue.platform.*
import com.tt.honeyDue.ui.components.common.clickableWithRipple
import com.tt.honeyDue.ui.components.common.minTouchTarget
import com.tt.honeyDue.ui.haptics.Haptics
import com.tt.honeyDue.ui.theme.*
import com.tt.honeyDue.viewmodel.ContractorViewModel
import org.jetbrains.compose.resources.stringResource

private const val MAX_IMAGES = 5

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun CompleteTaskScreen(
    taskId: Int,
    taskTitle: String,
    residenceName: String = "",
    onNavigateBack: () -> Unit,
    onComplete: (TaskCompletionCreateRequest, List<ImageData>) -> Unit,
    contractorViewModel: ContractorViewModel = viewModel { ContractorViewModel() }
) {
    var completedByName by remember { mutableStateOf("") }
    var actualCost by remember { mutableStateOf("") }
    var notes by remember { mutableStateOf("") }
    var rating by remember { mutableStateOf(3) }
    var selectedImages by remember { mutableStateOf<List<ImageData>>(emptyList()) }
    var selectedContractor by remember { mutableStateOf<ContractorSummary?>(null) }
    var showContractorPicker by remember { mutableStateOf(false) }
    var isSubmitting by remember { mutableStateOf(false) }

    val contractorsState by contractorViewModel.contractorsState.collectAsStateWithLifecycle()
    val hapticFeedback = rememberHapticFeedback()

    LaunchedEffect(Unit) {
        contractorViewModel.loadContractors()
    }

    val imagePicker = rememberImagePicker { images ->
        val newTotal = (selectedImages + images).take(MAX_IMAGES)
        selectedImages = newTotal
    }

    val cameraPicker = rememberCameraPicker { image ->
        if (selectedImages.size < MAX_IMAGES) {
            selectedImages = selectedImages + image
        }
    }

    WarmGradientBackground {
        Scaffold(
            containerColor = androidx.compose.ui.graphics.Color.Transparent,
            topBar = {
                TopAppBar(
                    title = {
                        Text(
                            stringResource(Res.string.completions_complete_task_title, taskTitle),
                            fontWeight = FontWeight.SemiBold,
                            maxLines = 1
                        )
                    },
                    navigationIcon = {
                        IconButton(
                            onClick = onNavigateBack,
                            modifier = Modifier.testTag(AccessibilityIds.Task.detailCancelButton)
                        ) {
                            Icon(Icons.Default.Close, contentDescription = stringResource(Res.string.common_cancel))
                        }
                    },
                    colors = TopAppBarDefaults.topAppBarColors(
                        containerColor = androidx.compose.ui.graphics.Color.Transparent
                    )
                )
            }
        ) { paddingValues ->
            Column(
                modifier = Modifier
                    .fillMaxSize()
                    .padding(paddingValues)
                    .imePadding()
                    .verticalScroll(rememberScrollState())
            ) {
                // Task Info Section
                OrganicCard(
                    modifier = Modifier
                        .fillMaxWidth()
                        .padding(horizontal = OrganicSpacing.lg, vertical = OrganicSpacing.md)
                ) {
                    Column(
                        modifier = Modifier.padding(OrganicSpacing.lg)
                    ) {
                        Text(
                            text = taskTitle,
                            style = MaterialTheme.typography.titleMedium,
                            fontWeight = FontWeight.SemiBold
                        )

                        Spacer(modifier = Modifier.height(OrganicSpacing.sm))

                        Row(
                            modifier = Modifier.fillMaxWidth(),
                            horizontalArrangement = Arrangement.SpaceBetween,
                            verticalAlignment = Alignment.CenterVertically
                        ) {
                            if (residenceName.isNotEmpty()) {
                                Row(
                                    verticalAlignment = Alignment.CenterVertically,
                                    horizontalArrangement = Arrangement.spacedBy(OrganicSpacing.xs)
                                ) {
                                    Icon(
                                        Icons.Default.Home,
                                        contentDescription = null, // decorative
                                        modifier = Modifier.size(16.dp),
                                        tint = MaterialTheme.colorScheme.onSurfaceVariant
                                    )
                                    Text(
                                        text = residenceName,
                                        style = MaterialTheme.typography.bodySmall,
                                        color = MaterialTheme.colorScheme.onSurfaceVariant
                                    )
                                }
                            }
                        }
                    }
                }

                // Contractor Section
                SectionHeader(
                    title = stringResource(Res.string.completions_select_contractor),
                    subtitle = stringResource(Res.string.completions_contractor_helper)
                )

                OrganicCard(
                    modifier = Modifier
                        .fillMaxWidth()
                        .padding(horizontal = OrganicSpacing.lg)
                        .clickableWithRipple(onClickLabel = "Select contractor") {
                            showContractorPicker = true
                        }
                ) {
                    Row(
                        modifier = Modifier
                            .fillMaxWidth()
                            .padding(OrganicSpacing.lg),
                        horizontalArrangement = Arrangement.SpaceBetween,
                        verticalAlignment = Alignment.CenterVertically
                    ) {
                        Row(
                            verticalAlignment = Alignment.CenterVertically,
                            horizontalArrangement = Arrangement.spacedBy(OrganicSpacing.md)
                        ) {
                            OrganicIconContainer(
                                icon = Icons.Default.Build,
                                size = 24.dp
                            )
                            Column {
                                Text(
                                    text = selectedContractor?.name
                                        ?: stringResource(Res.string.completions_none_manual),
                                    style = MaterialTheme.typography.bodyLarge
                                )
                                selectedContractor?.company?.let { company ->
                                    Text(
                                        text = company,
                                        style = MaterialTheme.typography.bodySmall,
                                        color = MaterialTheme.colorScheme.onSurfaceVariant
                                    )
                                }
                            }
                        }
                        Icon(
                            Icons.Default.ChevronRight,
                            contentDescription = null, // decorative
                            tint = MaterialTheme.colorScheme.onSurfaceVariant
                        )
                    }
                }

                Spacer(modifier = Modifier.height(OrganicSpacing.lg))

                // Completion Details Section
                SectionHeader(
                    title = stringResource(Res.string.completions_details_section),
                    subtitle = stringResource(Res.string.completions_optional_info)
                )

                Column(
                    modifier = Modifier.padding(horizontal = OrganicSpacing.lg),
                    verticalArrangement = Arrangement.spacedBy(OrganicSpacing.md)
                ) {
                    // Completed By Name
                    OutlinedTextField(
                        value = completedByName,
                        onValueChange = { completedByName = it },
                        label = { Text(stringResource(Res.string.completions_completed_by_name)) },
                        placeholder = { Text(stringResource(Res.string.completions_completed_by_placeholder)) },
                        leadingIcon = { Icon(Icons.Default.Person, null) },
                        modifier = Modifier.fillMaxWidth(),
                        singleLine = true,
                        enabled = selectedContractor == null,
                        shape = OrganicShapes.medium
                    )

                    // Actual Cost
                    OutlinedTextField(
                        value = actualCost,
                        onValueChange = { actualCost = it },
                        label = { Text(stringResource(Res.string.completions_actual_cost_optional)) },
                        leadingIcon = { Icon(Icons.Default.AttachMoney, null) },
                        prefix = { Text("$") },
                        modifier = Modifier
                            .fillMaxWidth()
                            .testTag(AccessibilityIds.Task.actualCostField),
                        singleLine = true,
                        keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Decimal),
                        shape = OrganicShapes.medium
                    )
                }

                Spacer(modifier = Modifier.height(OrganicSpacing.lg))

                // Notes Section
                SectionHeader(
                    title = stringResource(Res.string.completions_notes_optional),
                    subtitle = stringResource(Res.string.completions_notes_helper)
                )

                OutlinedTextField(
                    value = notes,
                    onValueChange = { notes = it },
                    placeholder = { Text(stringResource(Res.string.completions_notes_placeholder)) },
                    modifier = Modifier
                        .fillMaxWidth()
                        .padding(horizontal = OrganicSpacing.lg)
                        .height(120.dp)
                        .testTag(AccessibilityIds.Task.notesField),
                    shape = OrganicShapes.medium
                )

                Spacer(modifier = Modifier.height(OrganicSpacing.lg))

                // Rating Section
                SectionHeader(
                    title = stringResource(Res.string.completions_quality_rating),
                    subtitle = stringResource(Res.string.completions_rate_quality)
                )

                OrganicCard(
                    modifier = Modifier
                        .fillMaxWidth()
                        .padding(horizontal = OrganicSpacing.lg)
                ) {
                    Column(
                        modifier = Modifier
                            .fillMaxWidth()
                            .padding(OrganicSpacing.lg),
                        horizontalAlignment = Alignment.CenterHorizontally
                    ) {
                        Text(
                            text = "$rating / 5",
                            style = MaterialTheme.typography.titleMedium,
                            color = MaterialTheme.colorScheme.onSurfaceVariant
                        )

                        Spacer(modifier = Modifier.height(OrganicSpacing.md))

                        Row(
                            horizontalArrangement = Arrangement.Center,
                            verticalAlignment = Alignment.CenterVertically
                        ) {
                            (1..5).forEach { star ->
                                val isSelected = star <= rating
                                val starColor by animateColorAsState(
                                    targetValue = if (isSelected) Color(0xFFFFD700)
                                                 else MaterialTheme.colorScheme.onSurfaceVariant.copy(alpha = 0.3f),
                                    animationSpec = tween(durationMillis = 150),
                                    label = "starColor"
                                )

                                IconButton(
                                    onClick = {
                                        hapticFeedback.perform(HapticFeedbackType.Selection)
                                        rating = star
                                    },
                                    modifier = Modifier.size(56.dp)
                                ) {
                                    Icon(
                                        imageVector = if (isSelected) Icons.Default.Star else Icons.Default.StarOutline,
                                        contentDescription = "$star stars",
                                        tint = starColor,
                                        modifier = Modifier.size(40.dp)
                                    )
                                }
                            }
                        }
                    }
                }

                Spacer(modifier = Modifier.height(OrganicSpacing.lg))

                // Photos Section
                SectionHeader(
                    title = stringResource(Res.string.completions_photos_count, selectedImages.size, MAX_IMAGES),
                    subtitle = stringResource(Res.string.completions_add_photos_helper)
                )

                Column(
                    modifier = Modifier.padding(horizontal = OrganicSpacing.lg),
                    verticalArrangement = Arrangement.spacedBy(OrganicSpacing.md)
                ) {
                    Row(
                        modifier = Modifier.fillMaxWidth(),
                        horizontalArrangement = Arrangement.spacedBy(OrganicSpacing.md)
                    ) {
                        OutlinedButton(
                            onClick = {
                                hapticFeedback.perform(HapticFeedbackType.Light)
                                cameraPicker()
                            },
                            modifier = Modifier.weight(1f),
                            enabled = selectedImages.size < MAX_IMAGES
                        ) {
                            Icon(Icons.Default.CameraAlt, null, modifier = Modifier.size(20.dp))
                            Spacer(modifier = Modifier.width(OrganicSpacing.sm))
                            Text(stringResource(Res.string.completions_camera))
                        }

                        OutlinedButton(
                            onClick = {
                                hapticFeedback.perform(HapticFeedbackType.Light)
                                imagePicker()
                            },
                            modifier = Modifier.weight(1f),
                            enabled = selectedImages.size < MAX_IMAGES
                        ) {
                            Icon(Icons.Default.PhotoLibrary, null, modifier = Modifier.size(20.dp))
                            Spacer(modifier = Modifier.width(OrganicSpacing.sm))
                            Text(stringResource(Res.string.completions_library))
                        }
                    }

                    if (selectedImages.isNotEmpty()) {
                        Row(
                            modifier = Modifier
                                .fillMaxWidth()
                                .horizontalScroll(rememberScrollState()),
                            horizontalArrangement = Arrangement.spacedBy(OrganicSpacing.md)
                        ) {
                            selectedImages.forEachIndexed { index, imageData ->
                                ImageThumbnailCard(
                                    imageData = imageData,
                                    onRemove = {
                                        hapticFeedback.perform(HapticFeedbackType.Light)
                                        selectedImages = selectedImages.toMutableList().also {
                                            it.removeAt(index)
                                        }
                                    }
                                )
                            }
                        }
                    }
                }

                Spacer(modifier = Modifier.height(OrganicSpacing.xl))

                // Complete Button
                OrganicPrimaryButton(
                    text = stringResource(Res.string.completions_complete_button),
                    onClick = {
                        Haptics.success() // P5 Stream S — task completion haptic
                        isSubmitting = true
                        val notesWithContractor = buildString {
                            selectedContractor?.let {
                                append("Contractor: ${it.name}")
                                it.company?.let { company -> append(" ($company)") }
                                append("\n")
                            }
                            if (completedByName.isNotBlank()) {
                                append("Completed by: $completedByName\n")
                            }
                            if (notes.isNotBlank()) {
                                append(notes)
                            }
                        }.ifBlank { null }

                        onComplete(
                            TaskCompletionCreateRequest(
                                taskId = taskId,
                                completedAt = null,
                                actualCost = actualCost.ifBlank { null }?.toDoubleOrNull(),
                                notes = notesWithContractor,
                                rating = rating,
                                // upload_ids populated by the ViewModel after each
                                // image is uploaded directly to B2.
                            ),
                            selectedImages
                        )
                    },
                    modifier = Modifier
                        .fillMaxWidth()
                        .padding(horizontal = OrganicSpacing.lg)
                        .testTag(AccessibilityIds.Task.submitButton),
                    enabled = !isSubmitting,
                    isLoading = isSubmitting,
                    icon = Icons.Default.CheckCircle
                )

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

    // Contractor Picker Bottom Sheet
    if (showContractorPicker) {
        ContractorPickerSheet(
            contractors = when (val state = contractorsState) {
                is ApiResult.Success -> state.data
                else -> emptyList()
            },
            isLoading = contractorsState is ApiResult.Loading,
            selectedContractor = selectedContractor,
            onSelect = { contractor ->
                selectedContractor = contractor
                showContractorPicker = false
            },
            onDismiss = { showContractorPicker = false }
        )
    }
}

@Composable
private fun SectionHeader(
    title: String,
    subtitle: String? = null
) {
    Column(
        modifier = Modifier
            .fillMaxWidth()
            .padding(horizontal = OrganicSpacing.lg, vertical = OrganicSpacing.sm)
    ) {
        Text(
            text = title,
            style = MaterialTheme.typography.titleSmall,
            fontWeight = FontWeight.SemiBold,
            color = MaterialTheme.colorScheme.onSurface
        )
        subtitle?.let {
            Text(
                text = it,
                style = MaterialTheme.typography.bodySmall,
                color = MaterialTheme.colorScheme.onSurfaceVariant
            )
        }
    }
}

@Composable
private fun ImageThumbnailCard(
    imageData: ImageData,
    onRemove: () -> Unit
) {
    val imageBitmap = rememberImageBitmap(imageData)

    Box(
        modifier = Modifier
            .size(100.dp)
            .clip(OrganicShapes.medium)
            .background(MaterialTheme.colorScheme.surfaceVariant)
    ) {
        if (imageBitmap != null) {
            Image(
                bitmap = imageBitmap,
                contentDescription = imageData.fileName,
                modifier = Modifier.fillMaxSize(),
                contentScale = ContentScale.Crop
            )
        } else {
            Box(
                modifier = Modifier.fillMaxSize(),
                contentAlignment = Alignment.Center
            ) {
                Icon(
                    Icons.Default.PhotoLibrary,
                    contentDescription = null, // decorative
                    tint = MaterialTheme.colorScheme.onSurfaceVariant.copy(alpha = 0.5f),
                    modifier = Modifier.size(40.dp)
                )
            }
        }

        // Audit Phase 9b.2: wrap the 24dp visual badge in a 48dp touch target
        // with an explicit ripple so the affordance is reachable and feels
        // responsive. The outer Box carries the click; the inner Box keeps
        // the previous visual footprint.
        Box(
            modifier = Modifier
                .align(Alignment.TopEnd)
                .minTouchTarget()
                .clickableWithRipple(onClickLabel = "Remove photo", onClick = onRemove),
            contentAlignment = Alignment.Center,
        ) {
            Box(
                modifier = Modifier
                    .size(24.dp)
                    .clip(CircleShape)
                    .background(MaterialTheme.colorScheme.error),
                contentAlignment = Alignment.Center
            ) {
                Icon(
                    Icons.Default.Close,
                    contentDescription = null,
                    tint = MaterialTheme.colorScheme.onError,
                    modifier = Modifier.size(16.dp)
                )
            }
        }
    }
}

@OptIn(ExperimentalMaterial3Api::class)
@Composable
private fun ContractorPickerSheet(
    contractors: List<ContractorSummary>,
    isLoading: Boolean,
    selectedContractor: ContractorSummary?,
    onSelect: (ContractorSummary?) -> Unit,
    onDismiss: () -> Unit
) {
    val sheetState = rememberModalBottomSheetState()

    ModalBottomSheet(
        onDismissRequest = onDismiss,
        sheetState = sheetState
    ) {
        Column(
            modifier = Modifier
                .fillMaxWidth()
                .padding(bottom = OrganicSpacing.xl)
        ) {
            Text(
                text = stringResource(Res.string.completions_select_contractor),
                style = MaterialTheme.typography.titleLarge,
                fontWeight = FontWeight.Bold,
                modifier = Modifier.padding(horizontal = OrganicSpacing.lg, vertical = OrganicSpacing.md)
            )

            OrganicDivider()

            // None option
            ListItem(
                headlineContent = { Text(stringResource(Res.string.completions_none_manual)) },
                supportingContent = { Text(stringResource(Res.string.completions_enter_manually)) },
                trailingContent = {
                    if (selectedContractor == null) {
                        Icon(
                            Icons.Default.Check,
                            contentDescription = "Selected",
                            tint = MaterialTheme.colorScheme.primary
                        )
                    }
                },
                modifier = Modifier.clickable { onSelect(null) }
            )

            OrganicDivider()

            if (isLoading) {
                Box(
                    modifier = Modifier
                        .fillMaxWidth()
                        .padding(OrganicSpacing.xl),
                    contentAlignment = Alignment.Center
                ) {
                    CircularProgressIndicator()
                }
            } else {
                contractors.forEach { contractor ->
                    ListItem(
                        headlineContent = { Text(contractor.name) },
                        supportingContent = {
                            Column {
                                contractor.company?.let { Text(it) }
                            }
                        },
                        trailingContent = {
                            if (selectedContractor?.id == contractor.id) {
                                Icon(
                                    Icons.Default.Check,
                                    contentDescription = "Selected",
                                    tint = MaterialTheme.colorScheme.primary
                                )
                            }
                        },
                        modifier = Modifier.clickable { onSelect(contractor) }
                    )
                }
            }
        }
    }
}
