package com.tt.honeyDue.ui.screens.onboarding

import androidx.compose.animation.animateColorAsState
import androidx.compose.foundation.BorderStroke
import androidx.compose.foundation.layout.*
import androidx.compose.foundation.lazy.LazyColumn
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.ArrowForward
import androidx.compose.material3.*
import androidx.compose.runtime.*
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.text.style.TextAlign
import androidx.compose.ui.unit.dp
import androidx.lifecycle.compose.collectAsStateWithLifecycle
import com.tt.honeyDue.models.HomeProfileOptions
import com.tt.honeyDue.ui.theme.*
import com.tt.honeyDue.viewmodel.OnboardingViewModel
import honeydue.composeapp.generated.resources.*
import org.jetbrains.compose.resources.stringResource

@Composable
fun OnboardingHomeProfileContent(
    viewModel: OnboardingViewModel,
    onContinue: () -> Unit,
    onSkip: () -> Unit
) {
    val heatingType by viewModel.heatingType.collectAsStateWithLifecycle()
    val coolingType by viewModel.coolingType.collectAsStateWithLifecycle()
    val waterHeaterType by viewModel.waterHeaterType.collectAsStateWithLifecycle()
    val roofType by viewModel.roofType.collectAsStateWithLifecycle()
    val hasPool by viewModel.hasPool.collectAsStateWithLifecycle()
    val hasSprinklerSystem by viewModel.hasSprinklerSystem.collectAsStateWithLifecycle()
    val hasSeptic by viewModel.hasSeptic.collectAsStateWithLifecycle()
    val hasFireplace by viewModel.hasFireplace.collectAsStateWithLifecycle()
    val hasGarage by viewModel.hasGarage.collectAsStateWithLifecycle()
    val hasBasement by viewModel.hasBasement.collectAsStateWithLifecycle()
    val hasAttic by viewModel.hasAttic.collectAsStateWithLifecycle()
    val exteriorType by viewModel.exteriorType.collectAsStateWithLifecycle()
    val flooringPrimary by viewModel.flooringPrimary.collectAsStateWithLifecycle()
    val landscapingType by viewModel.landscapingType.collectAsStateWithLifecycle()

    Column(modifier = Modifier.fillMaxSize()) {
        LazyColumn(
            modifier = Modifier
                .fillMaxWidth()
                .weight(1f),
            contentPadding = PaddingValues(horizontal = OrganicSpacing.lg, vertical = OrganicSpacing.md)
        ) {
            // Header
            item {
                Column(
                    modifier = Modifier.fillMaxWidth(),
                    horizontalAlignment = Alignment.CenterHorizontally
                ) {
                    OrganicIconContainer(
                        icon = Icons.Default.Tune,
                        size = 80.dp,
                        iconSize = 40.dp,
                        gradientColors = listOf(
                            MaterialTheme.colorScheme.primary,
                            MaterialTheme.colorScheme.tertiary
                        ),
                        contentDescription = null // decorative
                    )

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

                    Text(
                        text = stringResource(Res.string.onboarding_home_profile_title),
                        style = MaterialTheme.typography.headlineMedium,
                        fontWeight = FontWeight.Bold,
                        color = MaterialTheme.colorScheme.onBackground
                    )

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

                    Text(
                        text = stringResource(Res.string.onboarding_home_profile_subtitle),
                        style = MaterialTheme.typography.bodyMedium,
                        color = MaterialTheme.colorScheme.onSurfaceVariant,
                        textAlign = TextAlign.Center
                    )

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

            // Systems section
            item {
                ProfileSectionHeader(
                    icon = Icons.Default.Settings,
                    title = stringResource(Res.string.onboarding_home_profile_systems)
                )
                Spacer(modifier = Modifier.height(OrganicSpacing.sm))
            }

            item {
                OptionDropdownChips(
                    label = "Heating",
                    options = HomeProfileOptions.heatingTypes,
                    selectedValue = heatingType,
                    onSelect = { viewModel.setHeatingType(it) }
                )
                Spacer(modifier = Modifier.height(OrganicSpacing.md))
            }

            item {
                OptionDropdownChips(
                    label = "Cooling",
                    options = HomeProfileOptions.coolingTypes,
                    selectedValue = coolingType,
                    onSelect = { viewModel.setCoolingType(it) }
                )
                Spacer(modifier = Modifier.height(OrganicSpacing.md))
            }

            item {
                OptionDropdownChips(
                    label = "Water Heater",
                    options = HomeProfileOptions.waterHeaterTypes,
                    selectedValue = waterHeaterType,
                    onSelect = { viewModel.setWaterHeaterType(it) }
                )
                Spacer(modifier = Modifier.height(OrganicSpacing.xl))
            }

            // Features section
            item {
                ProfileSectionHeader(
                    icon = Icons.Default.Star,
                    title = stringResource(Res.string.onboarding_home_profile_features)
                )
                Spacer(modifier = Modifier.height(OrganicSpacing.sm))
            }

            item {
                FlowRow(
                    modifier = Modifier.fillMaxWidth(),
                    horizontalArrangement = Arrangement.spacedBy(OrganicSpacing.sm),
                    verticalArrangement = Arrangement.spacedBy(OrganicSpacing.sm)
                ) {
                    ToggleChip(label = "Pool", selected = hasPool, onToggle = { viewModel.setHasPool(!hasPool) })
                    ToggleChip(label = "Sprinkler System", selected = hasSprinklerSystem, onToggle = { viewModel.setHasSprinklerSystem(!hasSprinklerSystem) })
                    ToggleChip(label = "Fireplace", selected = hasFireplace, onToggle = { viewModel.setHasFireplace(!hasFireplace) })
                    ToggleChip(label = "Garage", selected = hasGarage, onToggle = { viewModel.setHasGarage(!hasGarage) })
                    ToggleChip(label = "Basement", selected = hasBasement, onToggle = { viewModel.setHasBasement(!hasBasement) })
                    ToggleChip(label = "Attic", selected = hasAttic, onToggle = { viewModel.setHasAttic(!hasAttic) })
                    ToggleChip(label = "Septic", selected = hasSeptic, onToggle = { viewModel.setHasSeptic(!hasSeptic) })
                }
                Spacer(modifier = Modifier.height(OrganicSpacing.xl))
            }

            // Exterior section
            item {
                ProfileSectionHeader(
                    icon = Icons.Default.Roofing,
                    title = stringResource(Res.string.onboarding_home_profile_exterior)
                )
                Spacer(modifier = Modifier.height(OrganicSpacing.sm))
            }

            item {
                OptionDropdownChips(
                    label = "Roof Type",
                    options = HomeProfileOptions.roofTypes,
                    selectedValue = roofType,
                    onSelect = { viewModel.setRoofType(it) }
                )
                Spacer(modifier = Modifier.height(OrganicSpacing.md))
            }

            item {
                OptionDropdownChips(
                    label = "Exterior",
                    options = HomeProfileOptions.exteriorTypes,
                    selectedValue = exteriorType,
                    onSelect = { viewModel.setExteriorType(it) }
                )
                Spacer(modifier = Modifier.height(OrganicSpacing.xl))
            }

            // Interior section
            item {
                ProfileSectionHeader(
                    icon = Icons.Default.Weekend,
                    title = stringResource(Res.string.onboarding_home_profile_interior)
                )
                Spacer(modifier = Modifier.height(OrganicSpacing.sm))
            }

            item {
                OptionDropdownChips(
                    label = "Flooring",
                    options = HomeProfileOptions.flooringTypes,
                    selectedValue = flooringPrimary,
                    onSelect = { viewModel.setFlooringPrimary(it) }
                )
                Spacer(modifier = Modifier.height(OrganicSpacing.md))
            }

            item {
                OptionDropdownChips(
                    label = "Landscaping",
                    options = HomeProfileOptions.landscapingTypes,
                    selectedValue = landscapingType,
                    onSelect = { viewModel.setLandscapingType(it) }
                )
                Spacer(modifier = Modifier.height(100.dp)) // Space for bottom button
            }
        }

        // Bottom action area
        Surface(
            modifier = Modifier.fillMaxWidth(),
            shadowElevation = 8.dp
        ) {
            Column(
                modifier = Modifier.padding(OrganicSpacing.lg)
            ) {
                OrganicPrimaryButton(
                    text = stringResource(Res.string.onboarding_continue),
                    onClick = onContinue,
                    modifier = Modifier.fillMaxWidth(),
                    icon = Icons.AutoMirrored.Filled.ArrowForward
                )

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

                TextButton(
                    onClick = onSkip,
                    modifier = Modifier.fillMaxWidth()
                ) {
                    Text(
                        text = stringResource(Res.string.onboarding_skip),
                        style = MaterialTheme.typography.bodyMedium,
                        fontWeight = FontWeight.Medium,
                        color = MaterialTheme.colorScheme.onSurfaceVariant
                    )
                }
            }
        }
    }
}

@Composable
private fun ProfileSectionHeader(
    icon: androidx.compose.ui.graphics.vector.ImageVector,
    title: String
) {
    Row(
        verticalAlignment = Alignment.CenterVertically,
        horizontalArrangement = Arrangement.spacedBy(OrganicSpacing.sm)
    ) {
        Icon(
            imageVector = icon,
            contentDescription = null, // decorative
            modifier = Modifier.size(20.dp),
            tint = MaterialTheme.colorScheme.primary
        )
        Text(
            text = title,
            style = MaterialTheme.typography.titleMedium,
            fontWeight = FontWeight.SemiBold,
            color = MaterialTheme.colorScheme.onBackground
        )
    }
}

@Composable
private fun OptionDropdownChips(
    label: String,
    options: List<Pair<String, String>>,
    selectedValue: String?,
    onSelect: (String?) -> Unit
) {
    Column(modifier = Modifier.fillMaxWidth()) {
        Text(
            text = label,
            style = MaterialTheme.typography.bodySmall,
            fontWeight = FontWeight.Medium,
            color = MaterialTheme.colorScheme.onSurfaceVariant
        )
        Spacer(modifier = Modifier.height(OrganicSpacing.xs))
        FlowRow(
            modifier = Modifier.fillMaxWidth(),
            horizontalArrangement = Arrangement.spacedBy(OrganicSpacing.xs),
            verticalArrangement = Arrangement.spacedBy(OrganicSpacing.xs)
        ) {
            options.forEach { (apiValue, displayLabel) ->
                val isSelected = selectedValue == apiValue
                FilterChip(
                    selected = isSelected,
                    onClick = {
                        onSelect(if (isSelected) null else apiValue)
                    },
                    label = {
                        Text(
                            text = displayLabel,
                            style = MaterialTheme.typography.bodySmall
                        )
                    },
                    shape = RoundedCornerShape(OrganicRadius.lg),
                    colors = FilterChipDefaults.filterChipColors(
                        selectedContainerColor = MaterialTheme.colorScheme.primary.copy(alpha = 0.15f),
                        selectedLabelColor = MaterialTheme.colorScheme.primary
                    ),
                    border = BorderStroke(
                        width = 1.dp,
                        color = if (isSelected) MaterialTheme.colorScheme.primary.copy(alpha = 0.5f)
                                else MaterialTheme.colorScheme.outline.copy(alpha = 0.3f)
                    )
                )
            }
        }
    }
}

@Composable
private fun ToggleChip(
    label: String,
    selected: Boolean,
    onToggle: () -> Unit
) {
    val containerColor by animateColorAsState(
        targetValue = if (selected) {
            MaterialTheme.colorScheme.primary.copy(alpha = 0.15f)
        } else {
            MaterialTheme.colorScheme.surfaceVariant.copy(alpha = 0.5f)
        },
        label = "toggleChipColor"
    )
    val contentColor by animateColorAsState(
        targetValue = if (selected) {
            MaterialTheme.colorScheme.primary
        } else {
            MaterialTheme.colorScheme.onSurfaceVariant
        },
        label = "toggleChipContentColor"
    )

    FilterChip(
        selected = selected,
        onClick = onToggle,
        label = {
            Text(
                text = label,
                style = MaterialTheme.typography.bodyMedium,
                fontWeight = if (selected) FontWeight.Medium else FontWeight.Normal
            )
        },
        leadingIcon = if (selected) {
            {
                Icon(
                    Icons.Default.Check,
                    contentDescription = null, // decorative
                    modifier = Modifier.size(16.dp)
                )
            }
        } else null,
        shape = RoundedCornerShape(OrganicRadius.xl),
        colors = FilterChipDefaults.filterChipColors(
            containerColor = containerColor,
            labelColor = contentColor,
            iconColor = contentColor,
            selectedContainerColor = containerColor,
            selectedLabelColor = contentColor,
            selectedLeadingIconColor = contentColor
        ),
        border = FilterChipDefaults.filterChipBorder(
            borderColor = MaterialTheme.colorScheme.outline.copy(alpha = 0.3f),
            selectedBorderColor = MaterialTheme.colorScheme.primary.copy(alpha = 0.5f),
            enabled = true,
            selected = selected
        )
    )
}
