package com.tt.honeyDue.ui.components

import androidx.compose.foundation.layout.*
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.shape.RoundedCornerShape
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.Modifier
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.platform.testTag
import androidx.compose.ui.text.font.FontWeight
import com.tt.honeyDue.testing.AccessibilityIds
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.viewmodel.ResidenceViewModel
import com.tt.honeyDue.models.ContractorCreateRequest
import com.tt.honeyDue.models.ContractorUpdateRequest
import com.tt.honeyDue.models.Residence
import com.tt.honeyDue.network.ApiResult
import com.tt.honeyDue.repository.LookupsRepository
import com.tt.honeyDue.analytics.PostHogAnalytics
import com.tt.honeyDue.analytics.AnalyticsEvents
import com.tt.honeyDue.ui.theme.AppRadius
import com.tt.honeyDue.ui.theme.AppSpacing
import org.jetbrains.compose.resources.stringResource

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun AddContractorDialog(
    contractorId: Int? = null,
    onDismiss: () -> Unit,
    onContractorSaved: () -> Unit,
    viewModel: ContractorViewModel = viewModel { ContractorViewModel() },
    residenceViewModel: ResidenceViewModel = viewModel { ResidenceViewModel() }
) {
    val createState by viewModel.createState.collectAsState()
    val updateState by viewModel.updateState.collectAsState()
    val contractorDetailState by viewModel.contractorDetailState.collectAsState()
    val residencesState by residenceViewModel.residencesState.collectAsState()

    var name by remember { mutableStateOf("") }
    var company by remember { mutableStateOf("") }
    var phone by remember { mutableStateOf("") }
    var email by remember { mutableStateOf("") }
    var website by remember { mutableStateOf("") }
    var streetAddress by remember { mutableStateOf("") }
    var city by remember { mutableStateOf("") }
    var stateProvince by remember { mutableStateOf("") }
    var postalCode by remember { mutableStateOf("") }
    var notes by remember { mutableStateOf("") }
    var isFavorite by remember { mutableStateOf(false) }
    var selectedResidence by remember { mutableStateOf<Residence?>(null) }
    var selectedSpecialtyIds by remember { mutableStateOf<List<Int>>(emptyList()) }

    var expandedSpecialtyMenu by remember { mutableStateOf(false) }
    var expandedResidenceMenu by remember { mutableStateOf(false) }
    val contractorSpecialties by LookupsRepository.contractorSpecialties.collectAsState()

    // Track screen view and load residences for picker
    LaunchedEffect(Unit) {
        if (contractorId == null) {
            PostHogAnalytics.screen(AnalyticsEvents.NEW_CONTRACTOR_SCREEN_SHOWN)
        }
        residenceViewModel.loadResidences()
    }

    // Load existing contractor data if editing
    LaunchedEffect(contractorId) {
        if (contractorId != null) {
            viewModel.loadContractorDetail(contractorId)
        }
    }

    LaunchedEffect(contractorDetailState, residencesState) {
        if (contractorDetailState is ApiResult.Success) {
            val contractor = (contractorDetailState as ApiResult.Success).data
            name = contractor.name
            company = contractor.company ?: ""
            phone = contractor.phone ?: ""
            email = contractor.email ?: ""
            website = contractor.website ?: ""
            streetAddress = contractor.streetAddress ?: ""
            city = contractor.city ?: ""
            stateProvince = contractor.stateProvince ?: ""
            postalCode = contractor.postalCode ?: ""
            notes = contractor.notes ?: ""
            isFavorite = contractor.isFavorite
            selectedSpecialtyIds = contractor.specialties.map { it.id }

            // Set selected residence if contractor has one
            if (contractor.residenceId != null && residencesState is ApiResult.Success) {
                val residences = (residencesState as ApiResult.Success<List<Residence>>).data
                selectedResidence = residences.find { it.id == contractor.residenceId }
            }
        }
    }

    LaunchedEffect(createState) {
        if (createState is ApiResult.Success) {
            PostHogAnalytics.capture(AnalyticsEvents.CONTRACTOR_CREATED)
            onContractorSaved()
            viewModel.resetCreateState()
        }
    }

    LaunchedEffect(updateState) {
        if (updateState is ApiResult.Success) {
            onContractorSaved()
            viewModel.resetUpdateState()
        }
    }

    val dialogTitle = if (contractorId == null)
        stringResource(Res.string.contractors_form_add_title)
    else
        stringResource(Res.string.contractors_form_edit_title)
    val personalNoResidence = stringResource(Res.string.contractors_form_personal_no_residence)
    val cancelText = stringResource(Res.string.common_cancel)

    AlertDialog(
        onDismissRequest = onDismiss,
        modifier = Modifier.fillMaxWidth(0.95f),
        title = {
            Text(
                dialogTitle,
                fontWeight = FontWeight.Bold
            )
        },
        text = {
            Column(
                modifier = Modifier
                    .fillMaxWidth()
                    .heightIn(max = 500.dp)
                    .verticalScroll(rememberScrollState()),
                verticalArrangement = Arrangement.spacedBy(AppSpacing.md)
            ) {
                // Basic Information Section
                Text(
                    stringResource(Res.string.contractors_form_basic_info),
                    style = MaterialTheme.typography.titleSmall,
                    fontWeight = FontWeight.SemiBold,
                    color = Color(0xFF111827)
                )

                OutlinedTextField(
                    value = name,
                    onValueChange = { name = it },
                    label = { Text(stringResource(Res.string.contractors_form_name_required)) },
                    modifier = Modifier
                        .fillMaxWidth()
                        .testTag(AccessibilityIds.Contractor.nameField),
                    singleLine = true,
                    shape = RoundedCornerShape(AppRadius.md),
                    leadingIcon = { Icon(Icons.Default.Person, null) },
                    colors = OutlinedTextFieldDefaults.colors(
                        focusedBorderColor = Color(0xFF3B82F6),
                        unfocusedBorderColor = Color(0xFFE5E7EB)
                    )
                )

                OutlinedTextField(
                    value = company,
                    onValueChange = { company = it },
                    label = { Text(stringResource(Res.string.contractors_form_company)) },
                    modifier = Modifier
                        .fillMaxWidth()
                        .testTag(AccessibilityIds.Contractor.companyField),
                    singleLine = true,
                    shape = RoundedCornerShape(AppRadius.md),
                    leadingIcon = { Icon(Icons.Default.Business, null) },
                    colors = OutlinedTextFieldDefaults.colors(
                        focusedBorderColor = Color(0xFF3B82F6),
                        unfocusedBorderColor = Color(0xFFE5E7EB)
                    )
                )

                // Residence Picker (Optional)
                ExposedDropdownMenuBox(
                    expanded = expandedResidenceMenu,
                    onExpandedChange = { expandedResidenceMenu = it }
                ) {
                    OutlinedTextField(
                        value = selectedResidence?.name ?: personalNoResidence,
                        onValueChange = {},
                        readOnly = true,
                        label = { Text(stringResource(Res.string.contractors_form_residence_optional)) },
                        modifier = Modifier
                            .fillMaxWidth()
                            .menuAnchor(),
                        trailingIcon = { ExposedDropdownMenuDefaults.TrailingIcon(expanded = expandedResidenceMenu) },
                        shape = RoundedCornerShape(AppRadius.md),
                        leadingIcon = { Icon(Icons.Default.Home, null) },
                        colors = OutlinedTextFieldDefaults.colors(
                            focusedBorderColor = Color(0xFF3B82F6),
                            unfocusedBorderColor = Color(0xFFE5E7EB)
                        )
                    )

                    ExposedDropdownMenu(
                        expanded = expandedResidenceMenu,
                        onDismissRequest = { expandedResidenceMenu = false }
                    ) {
                        // Option for no residence (personal contractor)
                        DropdownMenuItem(
                            text = { Text(personalNoResidence) },
                            onClick = {
                                selectedResidence = null
                                expandedResidenceMenu = false
                            }
                        )

                        // List residences if loaded
                        if (residencesState is ApiResult.Success) {
                            val residences = (residencesState as ApiResult.Success<List<Residence>>).data
                            residences.forEach { residence ->
                                DropdownMenuItem(
                                    text = { Text(residence.name) },
                                    onClick = {
                                        selectedResidence = residence
                                        expandedResidenceMenu = false
                                    }
                                )
                            }
                        }
                    }
                }

                Text(
                    if (selectedResidence == null) stringResource(Res.string.contractors_form_personal_visibility)
                    else stringResource(Res.string.contractors_form_shared_visibility, selectedResidence?.name ?: ""),
                    style = MaterialTheme.typography.bodySmall,
                    color = Color(0xFF6B7280)
                )

                HorizontalDivider(modifier = Modifier.padding(vertical = AppSpacing.xs))

                // Contact Information Section
                Text(
                    stringResource(Res.string.contractors_form_contact_info),
                    style = MaterialTheme.typography.titleSmall,
                    fontWeight = FontWeight.SemiBold,
                    color = Color(0xFF111827)
                )

                OutlinedTextField(
                    value = phone,
                    onValueChange = { phone = it },
                    label = { Text(stringResource(Res.string.contractors_form_phone)) },
                    modifier = Modifier
                        .fillMaxWidth()
                        .testTag(AccessibilityIds.Contractor.phoneField),
                    singleLine = true,
                    shape = RoundedCornerShape(AppRadius.md),
                    leadingIcon = { Icon(Icons.Default.Phone, null) },
                    colors = OutlinedTextFieldDefaults.colors(
                        focusedBorderColor = Color(0xFF3B82F6),
                        unfocusedBorderColor = Color(0xFFE5E7EB)
                    )
                )

                OutlinedTextField(
                    value = email,
                    onValueChange = { email = it },
                    label = { Text(stringResource(Res.string.contractors_form_email)) },
                    modifier = Modifier
                        .fillMaxWidth()
                        .testTag(AccessibilityIds.Contractor.emailField),
                    singleLine = true,
                    shape = RoundedCornerShape(AppRadius.md),
                    leadingIcon = { Icon(Icons.Default.Email, null) },
                    colors = OutlinedTextFieldDefaults.colors(
                        focusedBorderColor = Color(0xFF3B82F6),
                        unfocusedBorderColor = Color(0xFFE5E7EB)
                    )
                )

                OutlinedTextField(
                    value = website,
                    onValueChange = { website = it },
                    label = { Text(stringResource(Res.string.contractors_form_website)) },
                    modifier = Modifier.fillMaxWidth(),
                    singleLine = true,
                    shape = RoundedCornerShape(AppRadius.md),
                    leadingIcon = { Icon(Icons.Default.Language, null) },
                    colors = OutlinedTextFieldDefaults.colors(
                        focusedBorderColor = Color(0xFF3B82F6),
                        unfocusedBorderColor = Color(0xFFE5E7EB)
                    )
                )

                HorizontalDivider(modifier = Modifier.padding(vertical = AppSpacing.xs))

                // Specialties Section
                Text(
                    stringResource(Res.string.contractors_form_specialties),
                    style = MaterialTheme.typography.titleSmall,
                    fontWeight = FontWeight.SemiBold,
                    color = Color(0xFF111827)
                )

                // Multi-select specialties using chips
                FlowRow(
                    modifier = Modifier.testTag(AccessibilityIds.Contractor.specialtyPicker),
                    horizontalArrangement = Arrangement.spacedBy(AppSpacing.sm),
                    verticalArrangement = Arrangement.spacedBy(AppSpacing.sm)
                ) {
                    contractorSpecialties.forEach { specialty ->
                        FilterChip(
                            selected = selectedSpecialtyIds.contains(specialty.id),
                            onClick = {
                                selectedSpecialtyIds = if (selectedSpecialtyIds.contains(specialty.id)) {
                                    selectedSpecialtyIds - specialty.id
                                } else {
                                    selectedSpecialtyIds + specialty.id
                                }
                            },
                            label = { Text(specialty.name) },
                            colors = FilterChipDefaults.filterChipColors(
                                selectedContainerColor = MaterialTheme.colorScheme.primary,
                                selectedLabelColor = MaterialTheme.colorScheme.onPrimary
                            )
                        )
                    }
                }

                HorizontalDivider(modifier = Modifier.padding(vertical = AppSpacing.xs))

                // Address Section
                Text(
                    stringResource(Res.string.contractors_form_address_section),
                    style = MaterialTheme.typography.titleSmall,
                    fontWeight = FontWeight.SemiBold,
                    color = Color(0xFF111827)
                )

                OutlinedTextField(
                    value = streetAddress,
                    onValueChange = { streetAddress = it },
                    label = { Text(stringResource(Res.string.contractors_form_street_address)) },
                    modifier = Modifier.fillMaxWidth(),
                    singleLine = true,
                    shape = RoundedCornerShape(AppRadius.md),
                    leadingIcon = { Icon(Icons.Default.LocationOn, null) },
                    colors = OutlinedTextFieldDefaults.colors(
                        focusedBorderColor = Color(0xFF3B82F6),
                        unfocusedBorderColor = Color(0xFFE5E7EB)
                    )
                )

                Row(horizontalArrangement = Arrangement.spacedBy(AppSpacing.sm)) {
                    OutlinedTextField(
                        value = city,
                        onValueChange = { city = it },
                        label = { Text(stringResource(Res.string.contractors_form_city)) },
                        modifier = Modifier.weight(1f),
                        singleLine = true,
                        shape = RoundedCornerShape(AppRadius.md),
                        colors = OutlinedTextFieldDefaults.colors(
                            focusedBorderColor = Color(0xFF3B82F6),
                            unfocusedBorderColor = Color(0xFFE5E7EB)
                        )
                    )

                    OutlinedTextField(
                        value = stateProvince,
                        onValueChange = { stateProvince = it },
                        label = { Text(stringResource(Res.string.contractors_form_state)) },
                        modifier = Modifier.weight(0.5f),
                        singleLine = true,
                        shape = RoundedCornerShape(AppRadius.md),
                        colors = OutlinedTextFieldDefaults.colors(
                            focusedBorderColor = Color(0xFF3B82F6),
                            unfocusedBorderColor = Color(0xFFE5E7EB)
                        )
                    )
                }

                OutlinedTextField(
                    value = postalCode,
                    onValueChange = { postalCode = it },
                    label = { Text(stringResource(Res.string.contractors_form_zip_code)) },
                    modifier = Modifier.fillMaxWidth(),
                    singleLine = true,
                    shape = RoundedCornerShape(AppRadius.md),
                    colors = OutlinedTextFieldDefaults.colors(
                        focusedBorderColor = Color(0xFF3B82F6),
                        unfocusedBorderColor = Color(0xFFE5E7EB)
                    )
                )

                HorizontalDivider(modifier = Modifier.padding(vertical = AppSpacing.xs))

                // Notes Section
                Text(
                    stringResource(Res.string.contractors_form_notes_section),
                    style = MaterialTheme.typography.titleSmall,
                    fontWeight = FontWeight.SemiBold,
                    color = Color(0xFF111827)
                )

                OutlinedTextField(
                    value = notes,
                    onValueChange = { notes = it },
                    label = { Text(stringResource(Res.string.contractors_form_private_notes)) },
                    modifier = Modifier
                        .fillMaxWidth()
                        .height(100.dp)
                        .testTag(AccessibilityIds.Contractor.notesField),
                    maxLines = 4,
                    shape = RoundedCornerShape(AppRadius.md),
                    leadingIcon = { Icon(Icons.Default.Notes, null) },
                    colors = OutlinedTextFieldDefaults.colors(
                        focusedBorderColor = Color(0xFF3B82F6),
                        unfocusedBorderColor = Color(0xFFE5E7EB)
                    )
                )

                // Favorite toggle
                Row(
                    modifier = Modifier.fillMaxWidth(),
                    horizontalArrangement = Arrangement.SpaceBetween
                ) {
                    Row {
                        Icon(
                            Icons.Default.Star,
                            contentDescription = null, // decorative
                            tint = if (isFavorite) Color(0xFFF59E0B) else Color(0xFF9CA3AF)
                        )
                        Spacer(modifier = Modifier.width(AppSpacing.sm))
                        Text(stringResource(Res.string.contractors_form_mark_favorite), color = Color(0xFF111827))
                    }
                    Switch(
                        checked = isFavorite,
                        onCheckedChange = { isFavorite = it },
                        colors = SwitchDefaults.colors(
                            checkedThumbColor = MaterialTheme.colorScheme.onPrimary,
                            checkedTrackColor = MaterialTheme.colorScheme.primary
                        )
                    )
                }

                // Error messages
                when (val state = if (contractorId == null) createState else updateState) {
                    is ApiResult.Error -> {
                        Text(
                            state.message,
                            color = Color(0xFFEF4444),
                            style = MaterialTheme.typography.bodySmall
                        )
                    }
                    else -> {}
                }
            }
        },
        confirmButton = {
            Button(
                onClick = {
                    if (name.isNotBlank()) {
                        if (contractorId == null) {
                            viewModel.createContractor(
                                ContractorCreateRequest(
                                    name = name,
                                    residenceId = selectedResidence?.id,
                                    company = company.takeIf { it.isNotBlank() },
                                    phone = phone.takeIf { it.isNotBlank() },
                                    email = email.takeIf { it.isNotBlank() },
                                    website = website.takeIf { it.isNotBlank() },
                                    streetAddress = streetAddress.takeIf { it.isNotBlank() },
                                    city = city.takeIf { it.isNotBlank() },
                                    stateProvince = stateProvince.takeIf { it.isNotBlank() },
                                    postalCode = postalCode.takeIf { it.isNotBlank() },
                                    isFavorite = isFavorite,
                                    notes = notes.takeIf { it.isNotBlank() },
                                    specialtyIds = selectedSpecialtyIds.takeIf { it.isNotEmpty() }
                                )
                            )
                        } else {
                            viewModel.updateContractor(
                                contractorId,
                                ContractorUpdateRequest(
                                    name = name,
                                    residenceId = selectedResidence?.id,
                                    company = company.takeIf { it.isNotBlank() },
                                    phone = phone.takeIf { it.isNotBlank() },
                                    email = email.takeIf { it.isNotBlank() },
                                    website = website.takeIf { it.isNotBlank() },
                                    streetAddress = streetAddress.takeIf { it.isNotBlank() },
                                    city = city.takeIf { it.isNotBlank() },
                                    stateProvince = stateProvince.takeIf { it.isNotBlank() },
                                    postalCode = postalCode.takeIf { it.isNotBlank() },
                                    isFavorite = isFavorite,
                                    notes = notes.takeIf { it.isNotBlank() },
                                    specialtyIds = selectedSpecialtyIds.takeIf { it.isNotEmpty() }
                                )
                            )
                        }
                    }
                },
                enabled = name.isNotBlank() &&
                         createState !is ApiResult.Loading && updateState !is ApiResult.Loading,
                colors = ButtonDefaults.buttonColors(
                    containerColor = Color(0xFF2563EB)
                ),
                modifier = Modifier.testTag(AccessibilityIds.Contractor.saveButton)
            ) {
                if (createState is ApiResult.Loading || updateState is ApiResult.Loading) {
                    CircularProgressIndicator(
                        modifier = Modifier.size(20.dp),
                        color = MaterialTheme.colorScheme.onPrimary,
                        strokeWidth = 2.dp
                    )
                } else {
                    Text(if (contractorId == null) stringResource(Res.string.contractors_form_add_button) else stringResource(Res.string.contractors_form_save_button))
                }
            }
        },
        dismissButton = {
            TextButton(
                onClick = onDismiss,
                modifier = Modifier.testTag(AccessibilityIds.Contractor.formCancelButton)
            ) {
                Text(cancelText, color = Color(0xFF6B7280))
            }
        },
        containerColor = MaterialTheme.colorScheme.surface,
        shape = RoundedCornerShape(AppRadius.lg)
    )
}
