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.material.icons.filled.Delete
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
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.support.enableTestTagsAsResourceId
import com.tt.honeyDue.viewmodel.ResidenceViewModel
import com.tt.honeyDue.repository.LookupsRepository
import com.tt.honeyDue.data.LocalDataManager
import com.tt.honeyDue.models.Residence
import com.tt.honeyDue.models.ResidenceCreateRequest
import com.tt.honeyDue.models.ResidenceType
import com.tt.honeyDue.models.ResidenceUser
import com.tt.honeyDue.network.ApiResult
import com.tt.honeyDue.network.APILayer
import com.tt.honeyDue.analytics.PostHogAnalytics
import com.tt.honeyDue.analytics.AnalyticsEvents
import com.tt.honeyDue.ui.theme.*
import honeydue.composeapp.generated.resources.*
import kotlinx.coroutines.launch
import org.jetbrains.compose.resources.stringResource

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun ResidenceFormScreen(
    existingResidence: Residence? = null,
    onNavigateBack: () -> Unit,
    onSuccess: () -> Unit,
    viewModel: ResidenceViewModel = viewModel { ResidenceViewModel() }
) {
    val isEditMode = existingResidence != null

    // Form state
    var name by remember { mutableStateOf(existingResidence?.name ?: "") }
    var propertyType by remember { mutableStateOf<ResidenceType?>(null) }
    var streetAddress by remember { mutableStateOf(existingResidence?.streetAddress ?: "") }
    var apartmentUnit by remember { mutableStateOf(existingResidence?.apartmentUnit ?: "") }
    var city by remember { mutableStateOf(existingResidence?.city ?: "") }
    var stateProvince by remember { mutableStateOf(existingResidence?.stateProvince ?: "") }
    var postalCode by remember { mutableStateOf(existingResidence?.postalCode ?: "") }
    var country by remember { mutableStateOf(existingResidence?.country ?: "USA") }
    var bedrooms by remember { mutableStateOf(existingResidence?.bedrooms?.toString() ?: "") }
    var bathrooms by remember { mutableStateOf(existingResidence?.bathrooms?.toString() ?: "") }
    var squareFootage by remember { mutableStateOf(existingResidence?.squareFootage?.toString() ?: "") }
    var lotSize by remember { mutableStateOf(existingResidence?.lotSize?.toString() ?: "") }
    var yearBuilt by remember { mutableStateOf(existingResidence?.yearBuilt?.toString() ?: "") }
    var description by remember { mutableStateOf(existingResidence?.description ?: "") }
    var isPrimary by remember { mutableStateOf(existingResidence?.isPrimary ?: false) }
    var expanded by remember { mutableStateOf(false) }

    val operationState by if (isEditMode) {
        viewModel.updateResidenceState.collectAsStateWithLifecycle()
    } else {
        viewModel.createResidenceState.collectAsStateWithLifecycle()
    }
    val dataManager = LocalDataManager.current
    val propertyTypes by LookupsRepository.residenceTypes.collectAsStateWithLifecycle()
    val currentUser by dataManager.currentUser.collectAsStateWithLifecycle()

    // Check if current user is the owner
    val isCurrentUserOwner = remember(existingResidence, currentUser) {
        existingResidence != null && currentUser != null && existingResidence.ownerId == currentUser?.id
    }

    // User management state (edit mode only, owner only)
    var users by remember { mutableStateOf<List<ResidenceUser>>(emptyList()) }
    var isLoadingUsers by remember { mutableStateOf(false) }
    var userToRemove by remember { mutableStateOf<ResidenceUser?>(null) }
    var showRemoveUserConfirmation by remember { mutableStateOf(false) }

    val scope = rememberCoroutineScope()

    // Load users when in edit mode and user is owner
    LaunchedEffect(isEditMode, isCurrentUserOwner, existingResidence?.id) {
        if (isEditMode && isCurrentUserOwner && existingResidence != null) {
            isLoadingUsers = true
            when (val result = APILayer.getResidenceUsers(existingResidence.id)) {
                is ApiResult.Success -> {
                    // Filter out the owner from the list
                    users = result.data.filter { it.id != existingResidence.ownerId }
                }
                is ApiResult.Error -> {
                    // Silently fail - users list will be empty
                }
                else -> {}
            }
            isLoadingUsers = false
        }
    }

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

    // Track screen view
    LaunchedEffect(Unit) {
        if (!isEditMode) {
            PostHogAnalytics.screen(AnalyticsEvents.NEW_RESIDENCE_SCREEN_SHOWN)
        }
    }

    // Handle operation state changes
    LaunchedEffect(operationState) {
        when (operationState) {
            is ApiResult.Success -> {
                if (isEditMode) {
                    viewModel.resetUpdateState()
                } else {
                    // Track residence created
                    PostHogAnalytics.capture(AnalyticsEvents.RESIDENCE_CREATED, mapOf(
                        "residence_type" to (propertyType?.name ?: "unknown")
                    ))
                    viewModel.resetCreateState()
                }
                onSuccess()
            }
            else -> {}
        }
    }

    // Set default/existing property type when types are loaded
    LaunchedEffect(propertyTypes, existingResidence) {
        if (propertyTypes.isNotEmpty() && propertyType == null) {
            propertyType = if (isEditMode && existingResidence != null && existingResidence.propertyTypeId != null) {
                propertyTypes.find { it.id == existingResidence.propertyTypeId }
            } else if (!isEditMode && propertyTypes.isNotEmpty()) {
                propertyTypes.first()
            } else {
                null
            }
        }
    }

    val nameRequiredError = stringResource(Res.string.properties_form_name_error)

    fun validateForm(): Boolean {
        var isValid = true

        if (name.isBlank()) {
            nameError = nameRequiredError
            isValid = false
        } else {
            nameError = ""
        }

        return isValid
    }

    Scaffold(
        modifier = Modifier.enableTestTagsAsResourceId(),
        topBar = {
            TopAppBar(
                title = { Text(if (isEditMode) stringResource(Res.string.properties_edit_title) else stringResource(Res.string.properties_add_title)) },
                navigationIcon = {
                    IconButton(
                        modifier = Modifier.testTag(AccessibilityIds.Residence.formCancelButton),
                        onClick = onNavigateBack
                    ) {
                        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)
            ) {
                // Basic Information section
                Text(
                    text = stringResource(Res.string.properties_details),
                    style = MaterialTheme.typography.titleMedium,
                    color = MaterialTheme.colorScheme.primary
                )

                OutlinedTextField(
                    value = name,
                    onValueChange = { name = it },
                    label = { Text(stringResource(Res.string.properties_form_name_required)) },
                    modifier = Modifier
                        .fillMaxWidth()
                        .testTag(AccessibilityIds.Residence.nameField),
                    isError = nameError.isNotEmpty(),
                    supportingText = if (nameError.isNotEmpty()) {
                        { Text(nameError, color = MaterialTheme.colorScheme.error) }
                    } else {
                        { Text(stringResource(Res.string.properties_form_required), color = MaterialTheme.colorScheme.error) }
                    }
                )

                ExposedDropdownMenuBox(
                    expanded = expanded,
                    onExpandedChange = { expanded = it }
                ) {
                    OutlinedTextField(
                        value = propertyType?.name?.replaceFirstChar { it.uppercase() } ?: "",
                        onValueChange = {},
                        readOnly = true,
                        label = { Text(stringResource(Res.string.properties_type_label)) },
                        trailingIcon = { ExposedDropdownMenuDefaults.TrailingIcon(expanded = expanded) },
                        modifier = Modifier
                            .fillMaxWidth()
                            .menuAnchor()
                            .testTag(AccessibilityIds.Residence.propertyTypePicker),
                        enabled = propertyTypes.isNotEmpty()
                    )
                    ExposedDropdownMenu(
                        expanded = expanded,
                        onDismissRequest = { expanded = false }
                    ) {
                        propertyTypes.forEach { type ->
                            DropdownMenuItem(
                                text = { Text(type.name.replaceFirstChar { it.uppercase() }) },
                                onClick = {
                                    propertyType = type
                                    expanded = false
                                }
                            )
                        }
                    }
                }

                // Address section
                Text(
                    text = stringResource(Res.string.properties_address_section),
                    style = MaterialTheme.typography.titleMedium,
                    color = MaterialTheme.colorScheme.primary
                )

                OutlinedTextField(
                    value = streetAddress,
                    onValueChange = { streetAddress = it },
                    label = { Text(stringResource(Res.string.properties_form_street)) },
                    modifier = Modifier
                        .fillMaxWidth()
                        .testTag(AccessibilityIds.Residence.streetAddressField)
                )

                OutlinedTextField(
                    value = apartmentUnit,
                    onValueChange = { apartmentUnit = it },
                    label = { Text(stringResource(Res.string.properties_form_apartment)) },
                    modifier = Modifier
                        .fillMaxWidth()
                        .testTag(AccessibilityIds.Residence.apartmentUnitField)
                )

                OutlinedTextField(
                    value = city,
                    onValueChange = { city = it },
                    label = { Text(stringResource(Res.string.properties_form_city)) },
                    modifier = Modifier
                        .fillMaxWidth()
                        .testTag(AccessibilityIds.Residence.cityField)
                )

                OutlinedTextField(
                    value = stateProvince,
                    onValueChange = { stateProvince = it },
                    label = { Text(stringResource(Res.string.properties_form_state)) },
                    modifier = Modifier
                        .fillMaxWidth()
                        .testTag(AccessibilityIds.Residence.stateProvinceField)
                )

                OutlinedTextField(
                    value = postalCode,
                    onValueChange = { postalCode = it },
                    label = { Text(stringResource(Res.string.properties_form_postal)) },
                    modifier = Modifier
                        .fillMaxWidth()
                        .testTag(AccessibilityIds.Residence.postalCodeField)
                )

                OutlinedTextField(
                    value = country,
                    onValueChange = { country = it },
                    label = { Text(stringResource(Res.string.properties_form_country)) },
                    modifier = Modifier
                        .fillMaxWidth()
                        .testTag(AccessibilityIds.Residence.countryField)
                )

                // Optional fields section
                OrganicDivider()
                Text(
                    text = stringResource(Res.string.properties_form_optional),
                    style = MaterialTheme.typography.titleMedium,
                    color = MaterialTheme.colorScheme.primary
                )

                Row(
                    modifier = Modifier.fillMaxWidth(),
                    horizontalArrangement = Arrangement.spacedBy(OrganicSpacing.compact)
                ) {
                    OutlinedTextField(
                        value = bedrooms,
                        onValueChange = { bedrooms = it.filter { char -> char.isDigit() } },
                        label = { Text(stringResource(Res.string.properties_bedrooms)) },
                        keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number),
                        modifier = Modifier
                            .weight(1f)
                            .testTag(AccessibilityIds.Residence.bedroomsField)
                    )

                    OutlinedTextField(
                        value = bathrooms,
                        onValueChange = { bathrooms = it },
                        label = { Text(stringResource(Res.string.properties_bathrooms)) },
                        keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Decimal),
                        modifier = Modifier
                            .weight(1f)
                            .testTag(AccessibilityIds.Residence.bathroomsField)
                    )
                }

                OutlinedTextField(
                    value = squareFootage,
                    onValueChange = { squareFootage = it.filter { char -> char.isDigit() } },
                    label = { Text(stringResource(Res.string.properties_form_sqft)) },
                    keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number),
                    modifier = Modifier
                        .fillMaxWidth()
                        .testTag(AccessibilityIds.Residence.squareFootageField)
                )

                OutlinedTextField(
                    value = lotSize,
                    onValueChange = { lotSize = it },
                    label = { Text(stringResource(Res.string.properties_form_lot_size)) },
                    keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Decimal),
                    modifier = Modifier
                        .fillMaxWidth()
                        .testTag(AccessibilityIds.Residence.lotSizeField)
                )

                OutlinedTextField(
                    value = yearBuilt,
                    onValueChange = { yearBuilt = it.filter { char -> char.isDigit() } },
                    label = { Text(stringResource(Res.string.properties_year_built)) },
                    keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number),
                    modifier = Modifier
                        .fillMaxWidth()
                        .testTag(AccessibilityIds.Residence.yearBuiltField)
                )

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

                Row(
                    modifier = Modifier.fillMaxWidth(),
                    horizontalArrangement = Arrangement.SpaceBetween
                ) {
                    Text(stringResource(Res.string.properties_form_primary))
                    Switch(
                        modifier = Modifier.testTag(AccessibilityIds.Residence.isPrimaryToggle),
                        checked = isPrimary,
                        onCheckedChange = { isPrimary = it }
                    )
                }

                // Users section (edit mode only, owner only)
                if (isEditMode && isCurrentUserOwner) {
                    OrganicDivider()
                    Text(
                        text = "Shared Users (${users.size})",
                        style = MaterialTheme.typography.titleMedium,
                        color = MaterialTheme.colorScheme.primary
                    )

                    if (isLoadingUsers) {
                        Box(
                            modifier = Modifier.fillMaxWidth().padding(OrganicSpacing.cozy),
                            contentAlignment = Alignment.Center
                        ) {
                            CircularProgressIndicator(modifier = Modifier.size(24.dp))
                        }
                    } else if (users.isEmpty()) {
                        Text(
                            text = "No shared users",
                            style = MaterialTheme.typography.bodyMedium,
                            color = MaterialTheme.colorScheme.onSurfaceVariant,
                            modifier = Modifier.padding(vertical = OrganicSpacing.compact)
                        )
                    } else {
                        users.forEach { user ->
                            UserListItem(
                                user = user,
                                onRemove = {
                                    userToRemove = user
                                    showRemoveUserConfirmation = true
                                }
                            )
                        }
                    }

                    Text(
                        text = "Users with access to this residence. Use the share button to invite others.",
                        style = MaterialTheme.typography.bodySmall,
                        color = MaterialTheme.colorScheme.onSurfaceVariant,
                        modifier = Modifier.padding(top = 4.dp)
                    )
                }

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

                // Submit button
                OrganicPrimaryButton(
                    modifier = Modifier.testTag(AccessibilityIds.Residence.saveButton),
                    text = if (isEditMode) stringResource(Res.string.properties_form_update) else stringResource(Res.string.properties_form_create),
                    onClick = {
                        if (validateForm()) {
                            val request = ResidenceCreateRequest(
                                name = name,
                                propertyTypeId = propertyType?.id,
                                streetAddress = streetAddress.ifBlank { null },
                                apartmentUnit = apartmentUnit.ifBlank { null },
                                city = city.ifBlank { null },
                                stateProvince = stateProvince.ifBlank { null },
                                postalCode = postalCode.ifBlank { null },
                                country = country.ifBlank { null },
                                bedrooms = bedrooms.toIntOrNull(),
                                bathrooms = bathrooms.toDoubleOrNull(),
                                squareFootage = squareFootage.toIntOrNull(),
                                lotSize = lotSize.toDoubleOrNull(),
                                yearBuilt = yearBuilt.toIntOrNull(),
                                description = description.ifBlank { null },
                                isPrimary = isPrimary
                            )

                            if (isEditMode && existingResidence != null) {
                                viewModel.updateResidence(existingResidence.id, request)
                            } else {
                                viewModel.createResidence(request)
                            }
                        }
                    },
                    enabled = validateForm(),
                    isLoading = operationState is ApiResult.Loading
                )

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

    // Remove user confirmation dialog
    if (showRemoveUserConfirmation && userToRemove != null) {
        AlertDialog(
            onDismissRequest = {
                showRemoveUserConfirmation = false
                userToRemove = null
            },
            title = { Text("Remove User") },
            text = {
                Text("Are you sure you want to remove ${userToRemove?.username} from this residence?")
            },
            confirmButton = {
                TextButton(
                    onClick = {
                        userToRemove?.let { user ->
                            scope.launch {
                                if (existingResidence != null) {
                                    when (APILayer.removeUser(existingResidence.id, user.id)) {
                                        is ApiResult.Success -> {
                                            users = users.filter { it.id != user.id }
                                        }
                                        is ApiResult.Error -> {
                                            // Silently fail
                                        }
                                        else -> {}
                                    }
                                }
                            }
                        }
                        showRemoveUserConfirmation = false
                        userToRemove = null
                    },
                    colors = ButtonDefaults.textButtonColors(
                        contentColor = MaterialTheme.colorScheme.error
                    )
                ) {
                    Text("Remove")
                }
            },
            dismissButton = {
                TextButton(
                    onClick = {
                        showRemoveUserConfirmation = false
                        userToRemove = null
                    }
                ) {
                    Text("Cancel")
                }
            }
        )
    }
}

@Composable
private fun UserListItem(
    user: ResidenceUser,
    onRemove: () -> Unit
) {
    OrganicCard(
        modifier = Modifier.fillMaxWidth().padding(vertical = 4.dp),
        showBlob = false
    ) {
        Row(
            modifier = Modifier.fillMaxWidth().padding(12.dp),
            horizontalArrangement = Arrangement.SpaceBetween,
            verticalAlignment = Alignment.CenterVertically
        ) {
            Column(modifier = Modifier.weight(1f)) {
                Text(
                    text = user.username,
                    style = MaterialTheme.typography.bodyLarge
                )
                if (!user.email.isNullOrEmpty()) {
                    Text(
                        text = user.email,
                        style = MaterialTheme.typography.bodySmall,
                        color = MaterialTheme.colorScheme.onSurfaceVariant
                    )
                }
                val fullName = listOfNotNull(user.firstName, user.lastName)
                    .filter { it.isNotEmpty() }
                    .joinToString(" ")
                if (fullName.isNotEmpty()) {
                    Text(
                        text = fullName,
                        style = MaterialTheme.typography.bodySmall,
                        color = MaterialTheme.colorScheme.onSurfaceVariant
                    )
                }
            }

            IconButton(onClick = onRemove) {
                Icon(
                    Icons.Default.Delete,
                    contentDescription = "Remove user",
                    tint = MaterialTheme.colorScheme.error
                )
            }
        }
    }
}
