package com.tt.honeyDue.ui.components

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.shape.RoundedCornerShape
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.Close
import androidx.compose.material.icons.filled.ArrowDropDown
import androidx.compose.material.icons.filled.Star
import androidx.compose.material.icons.filled.StarOutline
import androidx.compose.material.icons.filled.CameraAlt
import androidx.compose.material.icons.filled.PhotoLibrary
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.text.input.KeyboardType
import androidx.compose.ui.unit.dp
import androidx.lifecycle.viewmodel.compose.viewModel
import honeydue.composeapp.generated.resources.*
import com.tt.honeyDue.viewmodel.ContractorViewModel
import com.tt.honeyDue.models.TaskCompletionCreateRequest
import com.tt.honeyDue.network.ApiResult
import com.tt.honeyDue.platform.ImageData
import com.tt.honeyDue.platform.rememberImagePicker
import com.tt.honeyDue.platform.rememberCameraPicker
import com.tt.honeyDue.platform.HapticFeedbackType
import com.tt.honeyDue.platform.rememberHapticFeedback
import com.tt.honeyDue.ui.theme.AppRadius
import com.tt.honeyDue.ui.theme.AppSpacing
import com.tt.honeyDue.platform.rememberImageBitmap
import com.tt.honeyDue.ui.haptics.Haptics
import kotlinx.datetime.*
import org.jetbrains.compose.resources.stringResource

private const val MAX_IMAGES = 5

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun CompleteTaskDialog(
    taskId: Int,
    taskTitle: String,
    onDismiss: () -> 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 selectedContractorId by remember { mutableStateOf<Int?>(null) }
    var selectedContractorName by remember { mutableStateOf<String?>(null) }
    var showContractorDropdown by remember { mutableStateOf(false) }

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

    // Load contractors when dialog opens
    LaunchedEffect(Unit) {
        contractorViewModel.loadContractors()
    }

    val imagePicker = rememberImagePicker { images ->
        // Add new images up to the max limit
        val newTotal = (selectedImages + images).take(MAX_IMAGES)
        selectedImages = newTotal
    }

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

    val noneManualEntry = stringResource(Res.string.completions_none_manual)
    val cancelText = stringResource(Res.string.common_cancel)
    val removeImageDesc = stringResource(Res.string.completions_remove_image)

    AlertDialog(
        onDismissRequest = onDismiss,
        title = { Text(stringResource(Res.string.completions_complete_task_title, taskTitle)) },
        text = {
            Column(
                modifier = Modifier
                    .fillMaxWidth()
                    .verticalScroll(rememberScrollState()),
                verticalArrangement = Arrangement.spacedBy(AppSpacing.lg)
            ) {
                // Contractor Selection Dropdown
                ExposedDropdownMenuBox(
                    expanded = showContractorDropdown,
                    onExpandedChange = { showContractorDropdown = !showContractorDropdown }
                ) {
                    OutlinedTextField(
                        value = selectedContractorName ?: "",
                        onValueChange = {},
                        readOnly = true,
                        label = { Text(stringResource(Res.string.completions_select_contractor)) },
                        placeholder = { Text(stringResource(Res.string.completions_choose_contractor_placeholder)) },
                        trailingIcon = {
                            Icon(Icons.Default.ArrowDropDown, stringResource(Res.string.completions_expand))
                        },
                        modifier = Modifier
                            .fillMaxWidth()
                            .menuAnchor(),
                        colors = OutlinedTextFieldDefaults.colors()
                    )

                    ExposedDropdownMenu(
                        expanded = showContractorDropdown,
                        onDismissRequest = { showContractorDropdown = false }
                    ) {
                        // "None" option to clear selection
                        DropdownMenuItem(
                            text = { Text(noneManualEntry) },
                            onClick = {
                                selectedContractorId = null
                                selectedContractorName = null
                                showContractorDropdown = false
                            }
                        )

                        // Contractor list
                        when (val state = contractorsState) {
                            is ApiResult.Success -> {
                                state.data.forEach { contractor ->
                                    DropdownMenuItem(
                                        text = {
                                            Column {
                                                Text(contractor.name)
                                                contractor.company?.let { company ->
                                                    Text(
                                                        text = company,
                                                        style = MaterialTheme.typography.bodySmall,
                                                        color = MaterialTheme.colorScheme.onSurfaceVariant
                                                    )
                                                }
                                            }
                                        },
                                        onClick = {
                                            selectedContractorId = contractor.id
                                            selectedContractorName = if (contractor.company != null) {
                                                "${contractor.name} (${contractor.company})"
                                            } else {
                                                contractor.name
                                            }
                                            showContractorDropdown = false
                                        }
                                    )
                                }
                            }
                            is ApiResult.Loading -> {
                                DropdownMenuItem(
                                    text = { Text(stringResource(Res.string.completions_loading_contractors)) },
                                    onClick = {},
                                    enabled = false
                                )
                            }
                            is ApiResult.Error -> {
                                DropdownMenuItem(
                                    text = { Text(stringResource(Res.string.completions_error_loading_contractors)) },
                                    onClick = {},
                                    enabled = false
                                )
                            }
                            else -> {}
                        }
                    }
                }

                OutlinedTextField(
                    value = completedByName,
                    onValueChange = { completedByName = it },
                    label = { Text(stringResource(Res.string.completions_completed_by_name)) },
                    modifier = Modifier.fillMaxWidth(),
                    placeholder = { Text(stringResource(Res.string.completions_completed_by_placeholder)) },
                    enabled = selectedContractorId == null
                )

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

                OutlinedTextField(
                    value = notes,
                    onValueChange = { notes = it },
                    label = { Text(stringResource(Res.string.completions_notes_optional)) },
                    modifier = Modifier.fillMaxWidth(),
                    minLines = 3,
                    maxLines = 5
                )

                // Quality Rating Section - Interactive Stars
                Column {
                    Row(
                        modifier = Modifier.fillMaxWidth(),
                        horizontalArrangement = Arrangement.SpaceBetween,
                        verticalAlignment = Alignment.CenterVertically
                    ) {
                        Text(
                            text = stringResource(Res.string.completions_quality_rating),
                            style = MaterialTheme.typography.labelMedium
                        )
                        Text(
                            text = "$rating / 5",
                            style = MaterialTheme.typography.bodySmall,
                            color = MaterialTheme.colorScheme.onSurfaceVariant
                        )
                    }

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

                    // Interactive Star Rating
                    Row(
                        modifier = Modifier.fillMaxWidth(),
                        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(48.dp)
                            ) {
                                Icon(
                                    imageVector = if (isSelected) Icons.Default.Star else Icons.Default.StarOutline,
                                    contentDescription = "$star stars",
                                    tint = starColor,
                                    modifier = Modifier.size(32.dp)
                                )
                            }
                        }
                    }
                }

                // Image upload section with thumbnails
                Column {
                    Row(
                        modifier = Modifier.fillMaxWidth(),
                        horizontalArrangement = Arrangement.SpaceBetween,
                        verticalAlignment = Alignment.CenterVertically
                    ) {
                        Text(
                            text = stringResource(Res.string.completions_photos_count, selectedImages.size, MAX_IMAGES),
                            style = MaterialTheme.typography.labelMedium
                        )
                    }

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

                    // Photo buttons
                    Row(
                        modifier = Modifier.fillMaxWidth(),
                        horizontalArrangement = Arrangement.spacedBy(AppSpacing.sm)
                    ) {
                        OutlinedButton(
                            onClick = {
                                hapticFeedback.perform(HapticFeedbackType.Light)
                                cameraPicker()
                            },
                            modifier = Modifier.weight(1f),
                            enabled = selectedImages.size < MAX_IMAGES
                        ) {
                            Icon(
                                Icons.Default.CameraAlt,
                                contentDescription = null, // decorative
                                modifier = Modifier.size(18.dp)
                            )
                            Spacer(modifier = Modifier.width(AppSpacing.xs))
                            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,
                                contentDescription = null, // decorative
                                modifier = Modifier.size(18.dp)
                            )
                            Spacer(modifier = Modifier.width(AppSpacing.xs))
                            Text(stringResource(Res.string.completions_library))
                        }
                    }

                    // Image thumbnails with preview
                    if (selectedImages.isNotEmpty()) {
                        Spacer(modifier = Modifier.height(AppSpacing.md))

                        Row(
                            modifier = Modifier
                                .fillMaxWidth()
                                .horizontalScroll(rememberScrollState()),
                            horizontalArrangement = Arrangement.spacedBy(AppSpacing.sm)
                        ) {
                            selectedImages.forEachIndexed { index, imageData ->
                                ImageThumbnail(
                                    imageData = imageData,
                                    onRemove = {
                                        hapticFeedback.perform(HapticFeedbackType.Light)
                                        selectedImages = selectedImages.toMutableList().also {
                                            it.removeAt(index)
                                        }
                                    },
                                    removeContentDescription = removeImageDesc
                                )
                            }
                        }
                    }

                    // Helper text
                    Spacer(modifier = Modifier.height(AppSpacing.xs))
                    Text(
                        text = stringResource(Res.string.completions_add_photos_helper),
                        style = MaterialTheme.typography.bodySmall,
                        color = MaterialTheme.colorScheme.onSurfaceVariant
                    )
                }
            }
        },
        confirmButton = {
            Button(
                onClick = {
                    Haptics.success() // P5 Stream S — task completion haptic
                    // Get current date in ISO format
                    val currentDate = getCurrentDateTime()

                    // Build notes with contractor info if selected
                    val notesWithContractor = buildString {
                        if (selectedContractorName != null) {
                            append("Contractor: $selectedContractorName\n")
                        }
                        if (completedByName.isNotBlank()) {
                            append("Completed by: $completedByName\n")
                        }
                        if (notes.isNotBlank()) {
                            append(notes)
                        }
                    }.ifBlank { null }

                    onComplete(
                        TaskCompletionCreateRequest(
                            taskId = taskId,
                            completedAt = currentDate,
                            actualCost = actualCost.ifBlank { null }?.toDoubleOrNull(),
                            notes = notesWithContractor,
                            rating = rating,
                            // upload_ids populated by the ViewModel after each
                            // image is uploaded directly to B2.
                        ),
                        selectedImages
                    )
                }
            ) {
                Text(stringResource(Res.string.completions_complete_button))
            }
        },
        dismissButton = {
            TextButton(onClick = onDismiss) {
                Text(cancelText)
            }
        }
    )
}

// Helper function to get current date/time in ISO format
private fun getCurrentDateTime(): String {
    return kotlinx.datetime.LocalDate.toString()
}

/**
 * Image thumbnail with remove button for displaying selected images.
 */
@Composable
private fun ImageThumbnail(
    imageData: ImageData,
    onRemove: () -> Unit,
    removeContentDescription: String
) {
    val imageBitmap = rememberImageBitmap(imageData)

    Box(
        modifier = Modifier
            .size(80.dp)
            .clip(RoundedCornerShape(AppRadius.sm))
            .background(MaterialTheme.colorScheme.surfaceVariant)
    ) {
        if (imageBitmap != null) {
            Image(
                bitmap = imageBitmap,
                contentDescription = imageData.fileName,
                modifier = Modifier.fillMaxSize(),
                contentScale = ContentScale.Crop
            )
        } else {
            // Fallback placeholder
            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(32.dp)
                )
            }
        }

        // Remove button
        Box(
            modifier = Modifier
                .align(Alignment.TopEnd)
                .padding(AppSpacing.xs)
                .size(20.dp)
                .clip(CircleShape)
                .background(MaterialTheme.colorScheme.error)
                .clickable(onClick = onRemove),
            contentAlignment = Alignment.Center
        ) {
            Icon(
                Icons.Default.Close,
                contentDescription = removeContentDescription,
                tint = MaterialTheme.colorScheme.onError,
                modifier = Modifier.size(14.dp)
            )
        }
    }
}
