package com.tt.honeyDue.ui.screens

import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.*
import androidx.compose.material.icons.automirrored.filled.ArrowBack
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.font.FontWeight
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.ui.components.AddNewTaskDialog
import com.tt.honeyDue.ui.components.ApiResultHandler
import com.tt.honeyDue.ui.components.CompleteTaskDialog
import com.tt.honeyDue.ui.components.HandleErrors
import com.tt.honeyDue.ui.components.ManageUsersDialog
import com.tt.honeyDue.ui.components.common.CompactErrorState
import com.tt.honeyDue.ui.components.common.InfoCard
import com.tt.honeyDue.ui.components.residence.PropertyDetailItem
import com.tt.honeyDue.ui.components.residence.DetailRow
import com.tt.honeyDue.ui.components.task.TaskCard
import com.tt.honeyDue.ui.components.task.DynamicTaskKanbanView
import com.tt.honeyDue.viewmodel.ResidenceViewModel
import com.tt.honeyDue.viewmodel.TaskCompletionViewModel
import com.tt.honeyDue.viewmodel.TaskViewModel
import com.tt.honeyDue.models.Residence
import com.tt.honeyDue.models.TaskDetail
import com.tt.honeyDue.models.ContractorSummary
import com.tt.honeyDue.network.ApiResult
import com.tt.honeyDue.utils.SubscriptionHelper
import com.tt.honeyDue.ui.subscription.UpgradePromptDialog
import com.tt.honeyDue.data.LocalDataManager
import com.tt.honeyDue.util.DateUtils
import com.tt.honeyDue.platform.rememberShareResidence
import com.tt.honeyDue.analytics.PostHogAnalytics
import com.tt.honeyDue.analytics.AnalyticsEvents
import com.tt.honeyDue.ui.theme.*
import honeydue.composeapp.generated.resources.*
import org.jetbrains.compose.resources.stringResource

@OptIn(ExperimentalMaterial3Api::class)
@Composable
fun ResidenceDetailScreen(
    residenceId: Int,
    onNavigateBack: () -> Unit,
    onNavigateToEditResidence: (Residence) -> Unit,
    onNavigateToEditTask: (TaskDetail) -> Unit,
    onNavigateToContractorDetail: (Int) -> Unit = {},
    onNavigateToManageUsers: ((Int, String, Boolean, Int) -> Unit)? = null,
    residenceViewModel: ResidenceViewModel = viewModel { ResidenceViewModel() },
    taskCompletionViewModel: TaskCompletionViewModel = viewModel { TaskCompletionViewModel() },
    taskViewModel: TaskViewModel = viewModel { TaskViewModel() }
) {
    var residenceState by remember { mutableStateOf<ApiResult<Residence>>(ApiResult.Loading) }
    val tasksState by residenceViewModel.residenceTasksState.collectAsStateWithLifecycle()
    val contractorsState by residenceViewModel.residenceContractorsState.collectAsStateWithLifecycle()
    val completionState by taskCompletionViewModel.createCompletionState.collectAsStateWithLifecycle()
    val taskAddNewTaskState by taskViewModel.taskAddNewCustomTaskState.collectAsStateWithLifecycle()
    val cancelTaskState by residenceViewModel.cancelTaskState.collectAsStateWithLifecycle()
    val uncancelTaskState by residenceViewModel.uncancelTaskState.collectAsStateWithLifecycle()
    val generateReportState by residenceViewModel.generateReportState.collectAsStateWithLifecycle()

    var showCompleteDialog by remember { mutableStateOf(false) }
    var selectedTask by remember { mutableStateOf<TaskDetail?>(null) }
    var showNewTaskDialog by remember { mutableStateOf(false) }
    var showManageUsersDialog by remember { mutableStateOf(false) }
    var showReportSnackbar by remember { mutableStateOf(false) }
    var reportMessage by remember { mutableStateOf("") }
    var showReportConfirmation by remember { mutableStateOf(false) }
    var showDeleteConfirmation by remember { mutableStateOf(false) }
    var showCancelTaskConfirmation by remember { mutableStateOf(false) }
    var showArchiveTaskConfirmation by remember { mutableStateOf(false) }
    var taskToCancel by remember { mutableStateOf<TaskDetail?>(null) }
    var taskToArchive by remember { mutableStateOf<TaskDetail?>(null) }
    val deleteState by residenceViewModel.deleteResidenceState.collectAsStateWithLifecycle()
    var showUpgradePrompt by remember { mutableStateOf(false) }
    var upgradeTriggerKey by remember { mutableStateOf<String?>(null) }

    // Get current user for ownership checks
    val dataManager = LocalDataManager.current
    val currentUser by dataManager.currentUser.collectAsStateWithLifecycle()

    // Residence sharing state and function
    val (shareState, shareResidence) = rememberShareResidence()
    var showShareError by remember { mutableStateOf(false) }

    // Handle share error
    LaunchedEffect(shareState.error) {
        if (shareState.error != null) {
            showShareError = true
        }
    }

    // Check if tasks are blocked (limit=0) - this hides the FAB
    val isTasksBlocked = SubscriptionHelper.isTasksBlocked()
    // Get current count for checking when adding
    val currentTaskCount = (tasksState as? ApiResult.Success)?.data?.columns?.sumOf { it.tasks.size } ?: 0

    // Helper function to check if user can add a task
    fun canAddTask(): Pair<Boolean, String?> {
        val check = SubscriptionHelper.canAddTask(currentTaskCount)
        return Pair(check.allowed, check.triggerKey)
    }

    LaunchedEffect(residenceId) {
        residenceViewModel.getResidence(residenceId) { result ->
            residenceState = result
        }
        residenceViewModel.loadResidenceTasks(residenceId)
        residenceViewModel.loadResidenceContractors(residenceId)
    }

    // Handle completion success
    LaunchedEffect(completionState) {
        when (completionState) {
            is ApiResult.Success -> {
                showCompleteDialog = false
                selectedTask = null
                taskCompletionViewModel.resetCreateState()
                residenceViewModel.loadResidenceTasks(residenceId)
            }
            else -> {}
        }
    }

    LaunchedEffect(taskAddNewTaskState) {
        when (taskAddNewTaskState) {
            is ApiResult.Success -> {
                // Track task creation
                PostHogAnalytics.capture(
                    AnalyticsEvents.TASK_CREATED,
                    mapOf("residence_id" to residenceId)
                )
                showNewTaskDialog = false
                taskViewModel.resetAddTaskState()
                residenceViewModel.loadResidenceTasks(residenceId)
            }
            else -> {}
        }
    }

    // Handle cancel task success
    LaunchedEffect(cancelTaskState) {
        when (cancelTaskState) {
            is ApiResult.Success -> {
                residenceViewModel.resetCancelTaskState()
                residenceViewModel.loadResidenceTasks(residenceId)
            }
            else -> {}
        }
    }

    // Handle uncancel task success
    LaunchedEffect(uncancelTaskState) {
        when (uncancelTaskState) {
            is ApiResult.Success -> {
                residenceViewModel.resetUncancelTaskState()
                residenceViewModel.loadResidenceTasks(residenceId)
            }
            else -> {}
        }
    }

    // Handle generate report state
    // Handle errors for generate report
    generateReportState.HandleErrors(
        onRetry = { residenceViewModel.generateTasksReport(residenceId) },
        errorTitle = stringResource(Res.string.properties_failed_to_generate_report)
    )

    LaunchedEffect(generateReportState) {
        when (generateReportState) {
            is ApiResult.Success -> {
                val response = (generateReportState as ApiResult.Success).data
                reportMessage = response.message
                showReportSnackbar = true
                residenceViewModel.resetGenerateReportState()
            }
            else -> {}
        }
    }

    // Handle errors for delete residence
    deleteState.HandleErrors(
        onRetry = { residenceViewModel.deleteResidence(residenceId) },
        errorTitle = stringResource(Res.string.properties_failed_to_delete)
    )

    // Handle delete residence state
    LaunchedEffect(deleteState) {
        when (deleteState) {
            is ApiResult.Success -> {
                residenceViewModel.resetDeleteResidenceState()
                onNavigateBack()
            }
            else -> {}
        }
    }

    if (showCompleteDialog && selectedTask != null) {
        CompleteTaskDialog(
            taskId = selectedTask!!.id,
            taskTitle = selectedTask!!.title,
            onDismiss = {
                taskCompletionViewModel.resetCreateState()
            },
            onComplete = { request, images ->
                if (images.isNotEmpty()) {
                    taskCompletionViewModel.createTaskCompletionWithImages(
                        request = request,
                        images = images
                    )
                } else {
                    taskCompletionViewModel.createTaskCompletion(request)
                }
            }
        )
    }

    if (showNewTaskDialog) {
        AddNewTaskDialog(
            residenceId,
            onDismiss = {
            showNewTaskDialog = false
        }, onCreate = { request ->
                showNewTaskDialog = false
                taskViewModel.createNewTask(request)
        })
    }

    if (showUpgradePrompt && upgradeTriggerKey != null) {
        UpgradePromptDialog(
            triggerKey = upgradeTriggerKey!!,
            onDismiss = {
                showUpgradePrompt = false
                upgradeTriggerKey = null
            },
            onUpgrade = {
                // TODO: Navigate to subscription purchase screen
                showUpgradePrompt = false
                upgradeTriggerKey = null
            }
        )
    }

    if (showManageUsersDialog && residenceState is ApiResult.Success) {
        val residence = (residenceState as ApiResult.Success<Residence>).data
        ManageUsersDialog(
            residenceId = residence.id,
            residenceName = residence.name,
            isPrimaryOwner = residence.ownerId == currentUser?.id,
            residenceOwnerId = residence.ownerId,
            onDismiss = {
                showManageUsersDialog = false
            },
            onUserRemoved = {
                // Reload residence to update user count
                residenceViewModel.getResidence(residenceId) { result ->
                    residenceState = result
                }
            },
            onSharePackage = {
                // Use the existing share function with the residence
                shareResidence(residence)
            }
        )
    }

    if (showReportConfirmation) {
        AlertDialog(
            onDismissRequest = { showReportConfirmation = false },
            title = { Text(stringResource(Res.string.properties_generate_report)) },
            text = { Text(stringResource(Res.string.properties_generate_report_confirm)) },
            confirmButton = {
                Button(
                    onClick = {
                        showReportConfirmation = false
                        residenceViewModel.generateTasksReport(residenceId)
                    }
                ) {
                    Text(stringResource(Res.string.properties_generate))
                }
            },
            dismissButton = {
                TextButton(onClick = { showReportConfirmation = false }) {
                    Text(stringResource(Res.string.common_cancel))
                }
            }
        )
    }

    if (showDeleteConfirmation && residenceState is ApiResult.Success) {
        val residence = (residenceState as ApiResult.Success<Residence>).data
        AlertDialog(
            onDismissRequest = { showDeleteConfirmation = false },
            title = { Text(stringResource(Res.string.properties_delete_residence)) },
            text = { Text(stringResource(Res.string.properties_delete_name_confirm, residence.name)) },
            confirmButton = {
                Button(
                    modifier = Modifier.testTag(AccessibilityIds.Residence.confirmDeleteButton),
                    onClick = {
                        showDeleteConfirmation = false
                        residenceViewModel.deleteResidence(residenceId)
                    },
                    colors = ButtonDefaults.buttonColors(
                        containerColor = MaterialTheme.colorScheme.error
                    )
                ) {
                    Text(stringResource(Res.string.common_delete))
                }
            },
            dismissButton = {
                TextButton(onClick = { showDeleteConfirmation = false }) {
                    Text(stringResource(Res.string.common_cancel))
                }
            }
        )
    }

    if (showCancelTaskConfirmation && taskToCancel != null) {
        AlertDialog(
            onDismissRequest = {
                showCancelTaskConfirmation = false
                taskToCancel = null
            },
            title = { Text(stringResource(Res.string.properties_cancel_task)) },
            text = { Text(stringResource(Res.string.properties_cancel_task_confirm, taskToCancel!!.title)) },
            confirmButton = {
                Button(
                    onClick = {
                        showCancelTaskConfirmation = false
                        residenceViewModel.cancelTask(taskToCancel!!.id)
                        taskToCancel = null
                    },
                    colors = ButtonDefaults.buttonColors(
                        containerColor = MaterialTheme.colorScheme.error
                    )
                ) {
                    Text(stringResource(Res.string.properties_cancel_task))
                }
            },
            dismissButton = {
                TextButton(onClick = {
                    showCancelTaskConfirmation = false
                    taskToCancel = null
                }) {
                    Text(stringResource(Res.string.properties_dismiss))
                }
            }
        )
    }

    if (showArchiveTaskConfirmation && taskToArchive != null) {
        AlertDialog(
            onDismissRequest = {
                showArchiveTaskConfirmation = false
                taskToArchive = null
            },
            title = { Text(stringResource(Res.string.properties_archive_task)) },
            text = { Text(stringResource(Res.string.properties_archive_task_confirm, taskToArchive!!.title)) },
            confirmButton = {
                Button(
                    onClick = {
                        showArchiveTaskConfirmation = false
                        taskViewModel.archiveTask(taskToArchive!!.id) { success ->
                            if (success) {
                                residenceViewModel.loadResidenceTasks(residenceId)
                            }
                        }
                        taskToArchive = null
                    },
                    colors = ButtonDefaults.buttonColors(
                        containerColor = MaterialTheme.colorScheme.error
                    )
                ) {
                    Text(stringResource(Res.string.tasks_archive))
                }
            },
            dismissButton = {
                TextButton(onClick = {
                    showArchiveTaskConfirmation = false
                    taskToArchive = null
                }) {
                    Text(stringResource(Res.string.properties_dismiss))
                }
            }
        )
    }

    // Share error dialog
    if (showShareError && shareState.error != null) {
        AlertDialog(
            onDismissRequest = { showShareError = false },
            title = { Text(stringResource(Res.string.common_error)) },
            text = { Text(shareState.error ?: "Failed to share residence") },
            confirmButton = {
                TextButton(onClick = { showShareError = false }) {
                    Text(stringResource(Res.string.common_ok))
                }
            }
        )
    }

    val snackbarHostState = remember { SnackbarHostState() }

    LaunchedEffect(showReportSnackbar) {
        if (showReportSnackbar) {
            snackbarHostState.showSnackbar(reportMessage)
            showReportSnackbar = false
        }
    }

    Scaffold(
        modifier = Modifier
            .enableTestTagsAsResourceId()
            .testTag(AccessibilityIds.Residence.detailView),
        snackbarHost = { SnackbarHost(hostState = snackbarHostState) },
        topBar = {
            TopAppBar(
                title = { Text(stringResource(Res.string.properties_details), fontWeight = FontWeight.Bold) },
                navigationIcon = {
                    IconButton(onClick = onNavigateBack) {
                        Icon(Icons.AutoMirrored.Filled.ArrowBack, contentDescription = stringResource(Res.string.common_back))
                    }
                },
                actions = {
                    // Edit button - only show when residence is loaded
                    if (residenceState is ApiResult.Success) {
                        val residence = (residenceState as ApiResult.Success<Residence>).data

                        // Generate Report button
                        IconButton(
                            onClick = {
                                showReportConfirmation = true
                            },
                            enabled = generateReportState !is ApiResult.Loading
                        ) {
                            if (generateReportState is ApiResult.Loading) {
                                CircularProgressIndicator(
                                    modifier = Modifier.size(24.dp),
                                    strokeWidth = 2.dp
                                )
                            } else {
                                Icon(Icons.Default.Description, contentDescription = stringResource(Res.string.properties_generate_report))
                            }
                        }

                        // Share button - only show for primary owners
                        if (residence.ownerId == currentUser?.id) {
                            IconButton(
                                modifier = Modifier.testTag(AccessibilityIds.Residence.shareButton),
                                onClick = {
                                    val shareCheck = SubscriptionHelper.canShareResidence()
                                    if (shareCheck.allowed) {
                                        shareResidence(residence)
                                    } else {
                                        upgradeTriggerKey = shareCheck.triggerKey
                                        showUpgradePrompt = true
                                    }
                                },
                                enabled = !shareState.isLoading
                            ) {
                                if (shareState.isLoading) {
                                    CircularProgressIndicator(
                                        modifier = Modifier.size(24.dp),
                                        strokeWidth = 2.dp
                                    )
                                } else {
                                    Icon(Icons.Default.Share, contentDescription = stringResource(Res.string.common_share))
                                }
                            }
                        }

                        // Manage Users button - only show for primary owners
                        if (residence.ownerId == currentUser?.id) {
                            IconButton(
                                modifier = Modifier.testTag(AccessibilityIds.Residence.manageUsersButton),
                                onClick = {
                                    val shareCheck = SubscriptionHelper.canShareResidence()
                                    if (shareCheck.allowed) {
                                        if (onNavigateToManageUsers != null) {
                                            onNavigateToManageUsers(
                                                residence.id,
                                                residence.name,
                                                residence.ownerId == currentUser?.id,
                                                residence.ownerId
                                            )
                                        } else {
                                            showManageUsersDialog = true
                                        }
                                    } else {
                                        upgradeTriggerKey = shareCheck.triggerKey
                                        showUpgradePrompt = true
                                    }
                                }
                            ) {
                                Icon(Icons.Default.People, contentDescription = stringResource(Res.string.properties_manage_users))
                            }
                        }

                        IconButton(
                            modifier = Modifier.testTag(AccessibilityIds.Residence.editButton),
                            onClick = {
                                onNavigateToEditResidence(residence)
                            }
                        ) {
                            Icon(Icons.Default.Edit, contentDescription = stringResource(Res.string.properties_edit_residence))
                        }

                        // Delete button - only show for primary owners
                        if (residence.ownerId == currentUser?.id) {
                            IconButton(
                                modifier = Modifier.testTag(AccessibilityIds.Residence.deleteButton),
                                onClick = {
                                    showDeleteConfirmation = true
                                }
                            ) {
                                Icon(
                                    Icons.Default.Delete,
                                    contentDescription = stringResource(Res.string.properties_delete_residence),
                                    tint = MaterialTheme.colorScheme.error
                                )
                            }
                        }
                    }
                },
                colors = TopAppBarDefaults.topAppBarColors(
                    containerColor = MaterialTheme.colorScheme.surface
                )
            )
        },
        floatingActionButton = {
            // Don't show FAB if tasks are blocked (limit=0)
            if (!isTasksBlocked.allowed) {
                FloatingActionButton(
                    modifier = Modifier.testTag(AccessibilityIds.Residence.addTaskButton),
                    onClick = {
                        val (allowed, triggerKey) = canAddTask()
                        if (allowed) {
                            showNewTaskDialog = true
                        } else {
                            upgradeTriggerKey = triggerKey
                            showUpgradePrompt = true
                        }
                    },
                    containerColor = MaterialTheme.colorScheme.primary,
                    shape = RoundedCornerShape(16.dp)
                ) {
                    Icon(Icons.Default.Add, contentDescription = stringResource(Res.string.properties_add_task))
                }
            }
        }
    ) { paddingValues ->
        WarmGradientBackground {
            ApiResultHandler(
                state = residenceState,
                onRetry = {
                    residenceViewModel.getResidence(residenceId) { result ->
                        residenceState = result
                    }
                },
                modifier = Modifier.padding(paddingValues),
                errorTitle = stringResource(Res.string.properties_failed_to_load),
                loadingContent = {
                    Column(
                        horizontalAlignment = Alignment.CenterHorizontally,
                        verticalArrangement = Arrangement.spacedBy(OrganicSpacing.cozy)
                    ) {
                        CircularProgressIndicator()
                        Text(
                            text = stringResource(Res.string.properties_loading),
                            style = MaterialTheme.typography.bodyMedium,
                            color = MaterialTheme.colorScheme.onSurfaceVariant
                        )
                    }
                }
            ) { residence ->
                    LazyColumn(
                    modifier = Modifier
                        .fillMaxSize()
                        .padding(paddingValues),
                    contentPadding = PaddingValues(OrganicSpacing.cozy),
                    verticalArrangement = Arrangement.spacedBy(OrganicSpacing.cozy)
                ) {
                    // Property Header Card
                    item {
                        OrganicCard(
                            modifier = Modifier.fillMaxWidth(),
                            accentColor = MaterialTheme.colorScheme.primary,
                            showBlob = true,
                            blobVariation = 0
                        ) {
                            Column(
                                modifier = Modifier
                                    .fillMaxWidth()
                                    .padding(OrganicSpacing.comfortable)
                            ) {
                                Row(
                                    modifier = Modifier.fillMaxWidth(),
                                    horizontalArrangement = Arrangement.SpaceBetween,
                                    verticalAlignment = Alignment.CenterVertically
                                ) {
                                    Column(modifier = Modifier.weight(1f)) {
                                        Text(
                                            text = residence.name,
                                            style = MaterialTheme.typography.headlineMedium,
                                            fontWeight = FontWeight.Bold,
                                            color = MaterialTheme.colorScheme.textPrimary
                                        )
                                    }
                                }
                            }
                        }
                    }

                    // Address Card
                    if (residence.streetAddress != null || residence.city != null ||
                        residence.stateProvince != null || residence.postalCode != null ||
                        residence.country != null) {
                        item {
                            OrganicCard(
                                modifier = Modifier.fillMaxWidth(),
                                showBlob = true,
                                blobVariation = 1
                            ) {
                                Column(
                                    modifier = Modifier
                                        .fillMaxWidth()
                                        .padding(OrganicSpacing.cozy),
                                    verticalArrangement = Arrangement.spacedBy(OrganicSpacing.compact)
                                ) {
                                    Row(
                                        verticalAlignment = Alignment.CenterVertically,
                                        horizontalArrangement = Arrangement.spacedBy(OrganicSpacing.compact)
                                    ) {
                                        OrganicIconContainer(
                                            icon = Icons.Default.LocationOn,
                                            size = 40.dp,
                                            iconScale = 0.5f,
                                            backgroundColor = MaterialTheme.colorScheme.primary,
                                            iconColor = MaterialTheme.colorScheme.onPrimary
                                        )
                                        Text(
                                            text = stringResource(Res.string.properties_address_section),
                                            style = MaterialTheme.typography.titleMedium,
                                            fontWeight = FontWeight.Bold,
                                            color = MaterialTheme.colorScheme.textPrimary
                                        )
                                    }
                                    OrganicDivider(horizontalPadding = OrganicSpacing.compact)
                                    if (residence.streetAddress != null) {
                                        Text(
                                            text = residence.streetAddress,
                                            color = MaterialTheme.colorScheme.textSecondary
                                        )
                                    }
                                    if (residence.apartmentUnit != null) {
                                        Text(
                                            text = "Unit: ${residence.apartmentUnit}",
                                            color = MaterialTheme.colorScheme.textSecondary
                                        )
                                    }
                                    if (residence.city != null || residence.stateProvince != null || residence.postalCode != null) {
                                        Text(
                                            text = "${residence.city ?: ""}, ${residence.stateProvince ?: ""} ${residence.postalCode ?: ""}",
                                            color = MaterialTheme.colorScheme.textSecondary
                                        )
                                    }
                                    if (residence.country != null) {
                                        Text(
                                            text = residence.country,
                                            color = MaterialTheme.colorScheme.textSecondary
                                        )
                                    }
                                }
                            }
                        }
                    }

                    // Property Details Card
                    if (residence.bedrooms != null || residence.bathrooms != null ||
                        residence.squareFootage != null || residence.yearBuilt != null) {
                        item {
                            OrganicCard(
                                modifier = Modifier.fillMaxWidth(),
                                showBlob = true,
                                blobVariation = 2
                            ) {
                                Column(
                                    modifier = Modifier
                                        .fillMaxWidth()
                                        .padding(OrganicSpacing.cozy),
                                    verticalArrangement = Arrangement.spacedBy(OrganicSpacing.compact)
                                ) {
                                    Row(
                                        verticalAlignment = Alignment.CenterVertically,
                                        horizontalArrangement = Arrangement.spacedBy(OrganicSpacing.compact)
                                    ) {
                                        OrganicIconContainer(
                                            icon = Icons.Default.Info,
                                            size = 40.dp,
                                            iconScale = 0.5f,
                                            backgroundColor = MaterialTheme.colorScheme.primary,
                                            iconColor = MaterialTheme.colorScheme.onPrimary
                                        )
                                        Text(
                                            text = stringResource(Res.string.properties_property_details_section),
                                            style = MaterialTheme.typography.titleMedium,
                                            fontWeight = FontWeight.Bold,
                                            color = MaterialTheme.colorScheme.textPrimary
                                        )
                                    }
                                    OrganicDivider(horizontalPadding = OrganicSpacing.compact)
                                    Row(
                                        modifier = Modifier.fillMaxWidth(),
                                        horizontalArrangement = Arrangement.SpaceEvenly
                                    ) {
                                        residence.bedrooms?.let {
                                            PropertyDetailItem(Icons.Default.Bed, "$it", "Bedrooms")
                                        }
                                        residence.bathrooms?.let {
                                            PropertyDetailItem(Icons.Default.Bathroom, "$it", "Bathrooms")
                                        }
                                    }
                                    Spacer(modifier = Modifier.height(OrganicSpacing.compact))
                                    residence.squareFootage?.let {
                                        DetailRow(Icons.Default.SquareFoot, "Square Footage", "$it sq ft")
                                    }
                                    residence.lotSize?.let {
                                        DetailRow(Icons.Default.Landscape, "Lot Size", "$it acres")
                                    }
                                    residence.yearBuilt?.let {
                                        DetailRow(Icons.Default.CalendarToday, "Year Built", "$it")
                                    }
                                }
                            }
                        }
                    }

                    // Description Card
                    if (residence.description != null && !residence.description.isEmpty()) {
                        item {
                            OrganicCard(
                                modifier = Modifier.fillMaxWidth(),
                                showBlob = true,
                                blobVariation = 0
                            ) {
                                Column(
                                    modifier = Modifier
                                        .fillMaxWidth()
                                        .padding(OrganicSpacing.cozy),
                                    verticalArrangement = Arrangement.spacedBy(OrganicSpacing.compact)
                                ) {
                                    Row(
                                        verticalAlignment = Alignment.CenterVertically,
                                        horizontalArrangement = Arrangement.spacedBy(OrganicSpacing.compact)
                                    ) {
                                        OrganicIconContainer(
                                            icon = Icons.Default.Description,
                                            size = 40.dp,
                                            iconScale = 0.5f,
                                            backgroundColor = MaterialTheme.colorScheme.primary,
                                            iconColor = MaterialTheme.colorScheme.onPrimary
                                        )
                                        Text(
                                            text = stringResource(Res.string.properties_description_section),
                                            style = MaterialTheme.typography.titleMedium,
                                            fontWeight = FontWeight.Bold,
                                            color = MaterialTheme.colorScheme.textPrimary
                                        )
                                    }
                                    OrganicDivider(horizontalPadding = OrganicSpacing.compact)
                                    Text(
                                        text = residence.description,
                                        style = MaterialTheme.typography.bodyMedium,
                                        color = MaterialTheme.colorScheme.textSecondary
                                    )
                                }
                            }
                        }
                    }

                    // Purchase Information
                    if (residence.purchaseDate != null || residence.purchasePrice != null) {
                        item {
                            OrganicCard(
                                modifier = Modifier.fillMaxWidth(),
                                showBlob = true,
                                blobVariation = 1
                            ) {
                                Column(
                                    modifier = Modifier
                                        .fillMaxWidth()
                                        .padding(OrganicSpacing.cozy),
                                    verticalArrangement = Arrangement.spacedBy(OrganicSpacing.compact)
                                ) {
                                    Row(
                                        verticalAlignment = Alignment.CenterVertically,
                                        horizontalArrangement = Arrangement.spacedBy(OrganicSpacing.compact)
                                    ) {
                                        OrganicIconContainer(
                                            icon = Icons.Default.AttachMoney,
                                            size = 40.dp,
                                            iconScale = 0.5f,
                                            backgroundColor = MaterialTheme.colorScheme.primary,
                                            iconColor = MaterialTheme.colorScheme.onPrimary
                                        )
                                        Text(
                                            text = stringResource(Res.string.properties_purchase_info),
                                            style = MaterialTheme.typography.titleMedium,
                                            fontWeight = FontWeight.Bold,
                                            color = MaterialTheme.colorScheme.textPrimary
                                        )
                                    }
                                    OrganicDivider(horizontalPadding = OrganicSpacing.compact)
                                    residence.purchaseDate?.let {
                                        DetailRow(Icons.Default.Event, "Purchase Date", DateUtils.formatDateMedium(it))
                                    }
                                    residence.purchasePrice?.let {
                                        DetailRow(Icons.Default.Payment, "Purchase Price", "$$it")
                                    }
                                }
                            }
                        }
                    }

                    // Tasks Section Header
                    item {
                        Row(
                            modifier = Modifier
                                .fillMaxWidth()
                                .padding(vertical = OrganicSpacing.compact)
                                .testTag(AccessibilityIds.Residence.tasksSection),
                            verticalAlignment = Alignment.CenterVertically,
                            horizontalArrangement = Arrangement.spacedBy(OrganicSpacing.compact)
                        ) {
                            OrganicIconContainer(
                                icon = Icons.Default.Assignment,
                                size = 36.dp,
                                iconScale = 0.5f,
                                backgroundColor = MaterialTheme.colorScheme.primary,
                                iconColor = MaterialTheme.colorScheme.onPrimary
                            )
                            Text(
                                text = stringResource(Res.string.tasks_title),
                                style = MaterialTheme.typography.headlineSmall,
                                fontWeight = FontWeight.Bold,
                                color = MaterialTheme.colorScheme.textPrimary
                            )
                        }
                    }

                    when (tasksState) {
                        is ApiResult.Idle, is ApiResult.Loading -> {
                            item {
                                Box(
                                    modifier = Modifier
                                        .fillMaxWidth()
                                        .height(100.dp),
                                    contentAlignment = Alignment.Center
                                ) {
                                    CircularProgressIndicator()
                                }
                            }
                        }
                        is ApiResult.Error -> {
                            item {
                                CompactErrorState(
                                    message = "Error loading tasks: ${com.tt.honeyDue.util.ErrorMessageParser.parse((tasksState as ApiResult.Error).message)}",
                                    onRetry = { residenceViewModel.loadResidenceTasks(residenceId) }
                                )
                            }
                        }
                        is ApiResult.Success -> {
                            val taskData = (tasksState as ApiResult.Success).data
                            val allTasksEmpty = taskData.columns.all { it.tasks.isEmpty() }
                            if (allTasksEmpty) {
                                item {
                                    OrganicCard(
                                        modifier = Modifier.fillMaxWidth(),
                                        showBlob = true,
                                        blobVariation = 2
                                    ) {
                                        Column(
                                            modifier = Modifier
                                                .fillMaxWidth()
                                                .padding(OrganicSpacing.spacious),
                                            horizontalAlignment = Alignment.CenterHorizontally,
                                            verticalArrangement = Arrangement.spacedBy(OrganicSpacing.cozy)
                                        ) {
                                            OrganicIconContainer(
                                                icon = Icons.Default.Assignment,
                                                size = 64.dp,
                                                iconScale = 0.5f,
                                                backgroundColor = MaterialTheme.colorScheme.primary.copy(alpha = 0.3f),
                                                iconColor = MaterialTheme.colorScheme.primary
                                            )
                                            Text(
                                                stringResource(Res.string.properties_no_tasks),
                                                style = MaterialTheme.typography.titleLarge,
                                                fontWeight = FontWeight.SemiBold,
                                                color = MaterialTheme.colorScheme.textPrimary
                                            )
                                            Text(
                                                stringResource(Res.string.properties_add_task_start),
                                                style = MaterialTheme.typography.bodyMedium,
                                                color = MaterialTheme.colorScheme.textSecondary
                                            )
                                        }
                                    }
                                }
                            } else {
                                item {
                                    Box(
                                        modifier = Modifier
                                            .fillMaxWidth()
                                            .height(500.dp)
                                    ) {
                                        DynamicTaskKanbanView(
                                            columns = taskData.columns,
                                            onCompleteTask = { task ->
                                                selectedTask = task
                                                showCompleteDialog = true
                                            },
                                            onEditTask = { task ->
                                                onNavigateToEditTask(task)
                                            },
                                            onCancelTask = { task ->
                                                taskToCancel = task
                                                showCancelTaskConfirmation = true
                                            },
                                            onUncancelTask = { task ->
                                                residenceViewModel.uncancelTask(task.id)
                                            },
                                            onMarkInProgress = { task ->
                                                taskViewModel.markInProgress(task.id) { success ->
                                                    if (success) {
                                                        residenceViewModel.loadResidenceTasks(residenceId)
                                                    }
                                                }
                                            },
                                            onArchiveTask = { task ->
                                                taskToArchive = task
                                                showArchiveTaskConfirmation = true
                                            },
                                            onUnarchiveTask = { task ->
                                                taskViewModel.unarchiveTask(task.id) { success ->
                                                    if (success) {
                                                        residenceViewModel.loadResidenceTasks(residenceId)
                                                    }
                                                }
                                            }
                                        )
                                    }
                                }
                            }
                        }

                        else -> {}
                    }

                    // Contractors Section Header
                    item {
                        Spacer(modifier = Modifier.height(OrganicSpacing.cozy))
                        Row(
                            modifier = Modifier
                                .fillMaxWidth()
                                .padding(vertical = OrganicSpacing.compact),
                            verticalAlignment = Alignment.CenterVertically,
                            horizontalArrangement = Arrangement.spacedBy(OrganicSpacing.compact)
                        ) {
                            OrganicIconContainer(
                                icon = Icons.Default.People,
                                size = 36.dp,
                                iconScale = 0.5f,
                                backgroundColor = MaterialTheme.colorScheme.primary,
                                iconColor = MaterialTheme.colorScheme.onPrimary
                            )
                            Text(
                                text = stringResource(Res.string.contractors_title),
                                style = MaterialTheme.typography.headlineSmall,
                                fontWeight = FontWeight.Bold,
                                color = MaterialTheme.colorScheme.textPrimary
                            )
                        }
                    }

                    when (contractorsState) {
                        is ApiResult.Idle, is ApiResult.Loading -> {
                            item {
                                Box(
                                    modifier = Modifier
                                        .fillMaxWidth()
                                        .height(80.dp),
                                    contentAlignment = Alignment.Center
                                ) {
                                    CircularProgressIndicator()
                                }
                            }
                        }
                        is ApiResult.Error -> {
                            item {
                                CompactErrorState(
                                    message = "Error loading contractors: ${com.tt.honeyDue.util.ErrorMessageParser.parse((contractorsState as ApiResult.Error).message)}",
                                    onRetry = { residenceViewModel.loadResidenceContractors(residenceId) }
                                )
                            }
                        }
                        is ApiResult.Success -> {
                            val contractors = (contractorsState as ApiResult.Success<List<ContractorSummary>>).data
                            if (contractors.isEmpty()) {
                                item {
                                    OrganicCard(
                                        modifier = Modifier.fillMaxWidth(),
                                        showBlob = true,
                                        blobVariation = 1
                                    ) {
                                        Column(
                                            modifier = Modifier
                                                .fillMaxWidth()
                                                .padding(OrganicSpacing.comfortable),
                                            horizontalAlignment = Alignment.CenterHorizontally,
                                            verticalArrangement = Arrangement.spacedBy(OrganicSpacing.compact)
                                        ) {
                                            OrganicIconContainer(
                                                icon = Icons.Default.PersonAdd,
                                                size = 56.dp,
                                                iconScale = 0.5f,
                                                backgroundColor = MaterialTheme.colorScheme.primary.copy(alpha = 0.3f),
                                                iconColor = MaterialTheme.colorScheme.primary
                                            )
                                            Text(
                                                stringResource(Res.string.properties_no_contractors),
                                                style = MaterialTheme.typography.titleMedium,
                                                fontWeight = FontWeight.SemiBold,
                                                color = MaterialTheme.colorScheme.textPrimary
                                            )
                                            Text(
                                                stringResource(Res.string.properties_add_contractors_hint),
                                                style = MaterialTheme.typography.bodySmall,
                                                color = MaterialTheme.colorScheme.textSecondary
                                            )
                                        }
                                    }
                                }
                            } else {
                                items(contractors, key = { it.id }) { contractor ->
                                    ContractorCard(
                                        contractor = contractor,
                                        onToggleFavorite = { /* TODO: Implement in ResidenceViewModel if needed */ },
                                        onClick = { onNavigateToContractorDetail(contractor.id) }
                                    )
                                }
                            }
                        }
                        else -> {}
                    }

                    // Bottom spacing for FAB
                    item {
                        Spacer(modifier = Modifier.height(80.dp))
                    }
                }
            }
        }
    }
}
