import SwiftUI

/// Screen: Home profile — systems, features, exterior, interior
struct OnboardingHomeProfileContent: View {
    var onContinue: () -> Void
    var onSkip: () -> Void

    @ObservedObject private var onboardingState = OnboardingState.shared
    @State private var isAnimating = false
    @Environment(\.colorScheme) var colorScheme

    var body: some View {
        ZStack {
            WarmGradientBackground()
                .a11yDecorative()

            // Decorative blobs
            GeometryReader { geo in
                OrganicBlobShape(variation: 2)
                    .fill(
                        RadialGradient(
                            colors: [
                                Color.appAccent.opacity(0.08),
                                Color.appAccent.opacity(0.02),
                                Color.clear
                            ],
                            center: .center,
                            startRadius: 0,
                            endRadius: geo.size.width * 0.35
                        )
                    )
                    .frame(width: geo.size.width * 0.6, height: geo.size.height * 0.35)
                    .offset(x: -geo.size.width * 0.15, y: geo.size.height * 0.05)
                    .blur(radius: 25)

                OrganicBlobShape(variation: 0)
                    .fill(
                        RadialGradient(
                            colors: [
                                Color.appPrimary.opacity(0.06),
                                Color.appPrimary.opacity(0.01),
                                Color.clear
                            ],
                            center: .center,
                            startRadius: 0,
                            endRadius: geo.size.width * 0.3
                        )
                    )
                    .frame(width: geo.size.width * 0.5, height: geo.size.height * 0.3)
                    .offset(x: geo.size.width * 0.55, y: geo.size.height * 0.6)
                    .blur(radius: 20)
            }
            .a11yDecorative()

            VStack(spacing: 0) {
                ScrollView(showsIndicators: false) {
                    VStack(spacing: OrganicSpacing.comfortable) {
                        // Header
                        VStack(spacing: 16) {
                            ZStack {
                                Circle()
                                    .fill(
                                        RadialGradient(
                                            colors: [Color.appPrimary.opacity(0.15), Color.clear],
                                            center: .center,
                                            startRadius: 30,
                                            endRadius: 80
                                        )
                                    )
                                    .frame(width: 160, height: 160)
                                    .offset(x: -20, y: -20)
                                    .scaleEffect(isAnimating ? 1.1 : 1.0)
                                    .animation(
                                        isAnimating
                                            ? Animation.easeInOut(duration: 2.5).repeatForever(autoreverses: true)
                                            : .default,
                                        value: isAnimating
                                    )

                                Circle()
                                    .fill(
                                        RadialGradient(
                                            colors: [Color.appAccent.opacity(0.15), Color.clear],
                                            center: .center,
                                            startRadius: 30,
                                            endRadius: 80
                                        )
                                    )
                                    .frame(width: 160, height: 160)
                                    .offset(x: 20, y: 20)
                                    .scaleEffect(isAnimating ? 0.95 : 1.05)
                                    .animation(
                                        isAnimating
                                            ? Animation.easeInOut(duration: 3).repeatForever(autoreverses: true).delay(0.5)
                                            : .default,
                                        value: isAnimating
                                    )

                                ZStack {
                                    Circle()
                                        .fill(
                                            LinearGradient(
                                                colors: [Color.appPrimary, Color.appSecondary],
                                                startPoint: .topLeading,
                                                endPoint: .bottomTrailing
                                            )
                                        )
                                        .frame(width: 90, height: 90)

                                    Image(systemName: "house.lodge.fill")
                                        .font(.system(size: 40))
                                        .foregroundColor(.white)
                                }
                                .naturalShadow(.pronounced)
                            }

                            Text("Tell us about your home")
                                .font(.system(size: 26, weight: .bold, design: .rounded))
                                .foregroundColor(Color.appTextPrimary)
                                .multilineTextAlignment(.center)
                                .a11yHeader()

                            Text("All optional -- helps us personalize your plan")
                                .font(.system(size: 15, weight: .medium))
                                .foregroundColor(Color.appTextSecondary)
                                .multilineTextAlignment(.center)
                                .lineSpacing(4)
                        }
                        .padding(.top, OrganicSpacing.cozy)

                        // Systems section
                        ProfileSection(title: "Systems", icon: "gearshape.2.fill", color: .appPrimary) {
                            VStack(spacing: 12) {
                                ProfilePicker(
                                    label: "Heating",
                                    icon: "flame.fill",
                                    selection: $onboardingState.pendingHeatingType,
                                    options: HomeProfileOptions.heatingTypes
                                )
                                ProfilePicker(
                                    label: "Cooling",
                                    icon: "snowflake",
                                    selection: $onboardingState.pendingCoolingType,
                                    options: HomeProfileOptions.coolingTypes
                                )
                                ProfilePicker(
                                    label: "Water Heater",
                                    icon: "drop.fill",
                                    selection: $onboardingState.pendingWaterHeaterType,
                                    options: HomeProfileOptions.waterHeaterTypes
                                )
                            }
                        }

                        // Features section
                        ProfileSection(title: "Features", icon: "star.fill", color: .appAccent) {
                            HomeFeatureChipGrid(
                                features: [
                                    FeatureToggle(label: "Pool", icon: "figure.pool.swim", isOn: $onboardingState.pendingHasPool),
                                    FeatureToggle(label: "Sprinklers", icon: "sprinkler.and.droplets.fill", isOn: $onboardingState.pendingHasSprinklerSystem),
                                    FeatureToggle(label: "Fireplace", icon: "fireplace.fill", isOn: $onboardingState.pendingHasFireplace),
                                    FeatureToggle(label: "Garage", icon: "car.fill", isOn: $onboardingState.pendingHasGarage),
                                    FeatureToggle(label: "Basement", icon: "arrow.down.square.fill", isOn: $onboardingState.pendingHasBasement),
                                    FeatureToggle(label: "Attic", icon: "arrow.up.square.fill", isOn: $onboardingState.pendingHasAttic),
                                    FeatureToggle(label: "Septic", icon: "drop.triangle.fill", isOn: $onboardingState.pendingHasSeptic),
                                ]
                            )
                        }

                        // Exterior section
                        ProfileSection(title: "Exterior", icon: "house.fill", color: Color(hex: "#34C759") ?? .green) {
                            VStack(spacing: 12) {
                                ProfilePicker(
                                    label: "Roof Type",
                                    icon: "triangle.fill",
                                    selection: $onboardingState.pendingRoofType,
                                    options: HomeProfileOptions.roofTypes
                                )
                                ProfilePicker(
                                    label: "Exterior",
                                    icon: "square.stack.3d.up.fill",
                                    selection: $onboardingState.pendingExteriorType,
                                    options: HomeProfileOptions.exteriorTypes
                                )
                                ProfilePicker(
                                    label: "Landscaping",
                                    icon: "leaf.fill",
                                    selection: $onboardingState.pendingLandscapingType,
                                    options: HomeProfileOptions.landscapingTypes
                                )
                            }
                        }

                        // Interior section
                        ProfileSection(title: "Interior", icon: "sofa.fill", color: Color(hex: "#AF52DE") ?? .purple) {
                            ProfilePicker(
                                label: "Primary Flooring",
                                icon: "square.grid.3x3.fill",
                                selection: $onboardingState.pendingFlooringPrimary,
                                options: HomeProfileOptions.flooringTypes
                            )
                        }
                    }
                    .padding(.bottom, 140) // Space for button
                }

                // Bottom action area
                VStack(spacing: 14) {
                    Button(action: onContinue) {
                        HStack(spacing: 10) {
                            Text("Continue")
                                .font(.system(size: 17, weight: .bold))

                            Image(systemName: "arrow.right")
                                .font(.system(size: 16, weight: .bold))
                        }
                        .frame(maxWidth: .infinity)
                        .frame(height: 56)
                        .foregroundColor(Color.appTextOnPrimary)
                        .background(
                            LinearGradient(
                                colors: [Color.appPrimary, Color.appSecondary],
                                startPoint: .leading,
                                endPoint: .trailing
                            )
                        )
                        .clipShape(RoundedRectangle(cornerRadius: 16, style: .continuous))
                        .naturalShadow(.medium)
                    }
                }
                .padding(.horizontal, OrganicSpacing.comfortable)
                .padding(.bottom, OrganicSpacing.airy)
                .background(
                    LinearGradient(
                        colors: [Color.appBackgroundPrimary.opacity(0), Color.appBackgroundPrimary],
                        startPoint: .top,
                        endPoint: .center
                    )
                    .frame(height: 60)
                    .offset(y: -60)
                    , alignment: .top
                )
            }
        }
        .onAppear { isAnimating = true }
        .onDisappear { isAnimating = false }
    }
}

// MARK: - Profile Section Card

private struct ProfileSection<Content: View>: View {
    let title: String
    let icon: String
    let color: Color
    @ViewBuilder var content: Content

    @Environment(\.colorScheme) var colorScheme

    var body: some View {
        VStack(alignment: .leading, spacing: 14) {
            // Section header
            HStack(spacing: 10) {
                ZStack {
                    Circle()
                        .fill(
                            LinearGradient(
                                colors: [color, color.opacity(0.7)],
                                startPoint: .topLeading,
                                endPoint: .bottomTrailing
                            )
                        )
                        .frame(width: 32, height: 32)

                    Image(systemName: icon)
                        .font(.system(size: 14, weight: .semibold))
                        .foregroundColor(.white)
                }

                Text(title)
                    .font(.system(size: 16, weight: .bold, design: .rounded))
                    .foregroundColor(Color.appTextPrimary)
            }

            content
        }
        .padding(16)
        .background(
            ZStack {
                Color.appBackgroundSecondary
                GrainTexture(opacity: 0.01)
            }
        )
        .clipShape(RoundedRectangle(cornerRadius: 20, style: .continuous))
        .naturalShadow(.subtle)
        .padding(.horizontal, OrganicSpacing.comfortable)
    }
}

// MARK: - Profile Picker (compact dropdown)

private struct ProfilePicker: View {
    let label: String
    let icon: String
    @Binding var selection: String?
    let options: [HomeProfileOption]

    var body: some View {
        HStack(spacing: 12) {
            Image(systemName: icon)
                .font(.system(size: 16, weight: .medium))
                .foregroundColor(Color.appPrimary)
                .frame(width: 24)

            Text(label)
                .font(.system(size: 15, weight: .medium))
                .foregroundColor(Color.appTextPrimary)

            Spacer()

            Menu {
                Button("None") {
                    withAnimation(.spring(response: 0.3)) {
                        selection = nil
                    }
                }
                ForEach(options, id: \.value) { option in
                    Button(option.display) {
                        withAnimation(.spring(response: 0.3)) {
                            selection = option.value
                        }
                    }
                }
            } label: {
                Text(displayValue)
                    .font(.system(size: 14, weight: .semibold))
                    .foregroundColor(selection != nil ? Color.appPrimary : Color.appTextSecondary)
                +
                Text("  \(Image(systemName: "chevron.up.chevron.down"))")
                    .font(.system(size: 10, weight: .semibold))
                    .foregroundColor(Color.appTextSecondary)
            }
            .padding(.horizontal, 14)
            .padding(.vertical, 8)
            .background(
                (selection != nil ? Color.appPrimary : Color.appTextSecondary).opacity(0.1)
            )
            .clipShape(Capsule())
            .fixedSize()
        }
    }

    private var displayValue: String {
        guard let selection = selection else { return "Select" }
        return options.first { $0.value == selection }?.display ?? selection
    }
}

// MARK: - Feature Chip Toggle Grid

private struct FeatureToggle: Identifiable {
    let id = UUID()
    let label: String
    let icon: String
    @Binding var isOn: Bool
}

private struct HomeFeatureChipGrid: View {
    let features: [FeatureToggle]

    var body: some View {
        FlowLayout(spacing: 10) {
            ForEach(features) { feature in
                HomeFeatureChip(
                    label: feature.label,
                    icon: feature.icon,
                    isSelected: feature.isOn,
                    onTap: {
                        withAnimation(.spring(response: 0.2)) {
                            feature.isOn.toggle()
                        }
                    }
                )
            }
        }
    }
}

private struct HomeFeatureChip: View {
    let label: String
    let icon: String
    let isSelected: Bool
    var onTap: () -> Void

    var body: some View {
        Button(action: onTap) {
            HStack(spacing: 8) {
                Image(systemName: icon)
                    .font(.system(size: 14, weight: .medium))

                Text(label)
                    .font(.system(size: 14, weight: .semibold))
            }
            .foregroundColor(isSelected ? .white : Color.appTextPrimary)
            .padding(.horizontal, 16)
            .padding(.vertical, 10)
            .background(
                isSelected
                    ? AnyShapeStyle(LinearGradient(
                        colors: [Color.appPrimary, Color.appSecondary],
                        startPoint: .topLeading,
                        endPoint: .bottomTrailing
                    ))
                    : AnyShapeStyle(Color.appTextSecondary.opacity(0.1))
            )
            .clipShape(Capsule())
            .overlay(
                Capsule()
                    .stroke(
                        isSelected ? Color.clear : Color.appTextSecondary.opacity(0.2),
                        lineWidth: 1
                    )
            )
        }
        .buttonStyle(.plain)
        .accessibilityLabel(label)
        .accessibilityValue(isSelected ? "selected" : "not selected")
    }
}

// MARK: - Home Profile Options

struct HomeProfileOption {
    let value: String
    let display: String
}

enum HomeProfileOptions {
    static let heatingTypes: [HomeProfileOption] = [
        HomeProfileOption(value: "gas_furnace", display: "Gas Furnace"),
        HomeProfileOption(value: "electric_furnace", display: "Electric Furnace"),
        HomeProfileOption(value: "heat_pump", display: "Heat Pump"),
        HomeProfileOption(value: "boiler", display: "Boiler"),
        HomeProfileOption(value: "radiant", display: "Radiant"),
        HomeProfileOption(value: "other", display: "Other"),
    ]

    static let coolingTypes: [HomeProfileOption] = [
        HomeProfileOption(value: "central_ac", display: "Central AC"),
        HomeProfileOption(value: "window_ac", display: "Window AC"),
        HomeProfileOption(value: "heat_pump", display: "Heat Pump"),
        HomeProfileOption(value: "evaporative", display: "Evaporative"),
        HomeProfileOption(value: "none", display: "None"),
        HomeProfileOption(value: "other", display: "Other"),
    ]

    static let waterHeaterTypes: [HomeProfileOption] = [
        HomeProfileOption(value: "tank_gas", display: "Tank (Gas)"),
        HomeProfileOption(value: "tank_electric", display: "Tank (Electric)"),
        HomeProfileOption(value: "tankless_gas", display: "Tankless (Gas)"),
        HomeProfileOption(value: "tankless_electric", display: "Tankless (Electric)"),
        HomeProfileOption(value: "heat_pump", display: "Heat Pump"),
        HomeProfileOption(value: "solar", display: "Solar"),
        HomeProfileOption(value: "other", display: "Other"),
    ]

    static let roofTypes: [HomeProfileOption] = [
        HomeProfileOption(value: "asphalt_shingle", display: "Asphalt Shingle"),
        HomeProfileOption(value: "metal", display: "Metal"),
        HomeProfileOption(value: "tile", display: "Tile"),
        HomeProfileOption(value: "slate", display: "Slate"),
        HomeProfileOption(value: "wood_shake", display: "Wood Shake"),
        HomeProfileOption(value: "flat", display: "Flat"),
        HomeProfileOption(value: "other", display: "Other"),
    ]

    static let exteriorTypes: [HomeProfileOption] = [
        HomeProfileOption(value: "brick", display: "Brick"),
        HomeProfileOption(value: "vinyl_siding", display: "Vinyl Siding"),
        HomeProfileOption(value: "wood_siding", display: "Wood Siding"),
        HomeProfileOption(value: "stucco", display: "Stucco"),
        HomeProfileOption(value: "stone", display: "Stone"),
        HomeProfileOption(value: "fiber_cement", display: "Fiber Cement"),
        HomeProfileOption(value: "other", display: "Other"),
    ]

    static let flooringTypes: [HomeProfileOption] = [
        HomeProfileOption(value: "hardwood", display: "Hardwood"),
        HomeProfileOption(value: "laminate", display: "Laminate"),
        HomeProfileOption(value: "tile", display: "Tile"),
        HomeProfileOption(value: "carpet", display: "Carpet"),
        HomeProfileOption(value: "vinyl", display: "Vinyl"),
        HomeProfileOption(value: "concrete", display: "Concrete"),
        HomeProfileOption(value: "other", display: "Other"),
    ]

    static let landscapingTypes: [HomeProfileOption] = [
        HomeProfileOption(value: "lawn", display: "Lawn"),
        HomeProfileOption(value: "desert", display: "Desert"),
        HomeProfileOption(value: "xeriscape", display: "Xeriscape"),
        HomeProfileOption(value: "garden", display: "Garden"),
        HomeProfileOption(value: "mixed", display: "Mixed"),
        HomeProfileOption(value: "none", display: "None"),
        HomeProfileOption(value: "other", display: "Other"),
    ]
}

// MARK: - Preview

#Preview {
    OnboardingHomeProfileContent(
        onContinue: {},
        onSkip: {}
    )
}
