import SwiftUI
import ComposeApp

struct PropertyHeaderCard: View {
    let residence: ResidenceResponse
    @Environment(\.colorScheme) var colorScheme

    var body: some View {
        VStack(alignment: .leading, spacing: 0) {
            // Header Section
            HStack(alignment: .top, spacing: 16) {
                // Property Icon
                PropertyDetailIcon()

                // Property Info
                VStack(alignment: .leading, spacing: 6) {
                    Text(residence.name)
                        .font(.system(size: 24, weight: .bold, design: .rounded))
                        .foregroundColor(Color.appTextPrimary)
                        .accessibilityAddTraits(.isHeader)

                    if let propertyTypeName = residence.propertyTypeName {
                        Text(propertyTypeName.uppercased())
                            .font(.system(size: 11, weight: .semibold, design: .rounded))
                            .foregroundColor(Color.appTextSecondary)
                            .tracking(1.5)
                    }
                }

                Spacer()

                // Primary badge if applicable
                if residence.isPrimary {
                    HStack(spacing: 4) {
                        Image(systemName: "star.fill")
                            .font(.system(size: 11, weight: .bold))

                        Text("Primary")
                            .font(.system(size: 11, weight: .semibold))
                    }
                    .foregroundColor(Color.appAccent)
                    .padding(.horizontal, 10)
                    .padding(.vertical, 6)
                    .background(
                        Capsule()
                            .fill(Color.appAccent.opacity(0.12))
                    )
                }
            }
            .padding(.horizontal, OrganicSpacing.cozy)
            .padding(.top, OrganicSpacing.cozy)
            .padding(.bottom, 20)

            // Divider
            OrganicDivider()
                .padding(.horizontal, 20)

            // Address Section
            VStack(alignment: .leading, spacing: 10) {
                if !residence.streetAddress.isEmpty {
                    HStack(spacing: 10) {
                        ZStack {
                            Circle()
                                .fill(Color.appPrimary.opacity(0.1))
                                .frame(width: 32, height: 32)

                            Image(systemName: "mappin.circle.fill")
                                .font(.system(size: 14, weight: .semibold))
                                .foregroundColor(Color.appPrimary)
                        }

                        Text(residence.streetAddress)
                            .font(.system(size: 15, weight: .medium))
                            .foregroundColor(Color.appTextPrimary)
                    }
                }

                if !residence.city.isEmpty || !residence.stateProvince.isEmpty || !residence.postalCode.isEmpty {
                    HStack(spacing: 10) {
                        Color.clear.frame(width: 32, height: 1) // Alignment spacer

                        Text({
                            var parts: [String] = []
                            let cityState = [residence.city, residence.stateProvince]
                                .filter { !$0.isEmpty }
                                .joined(separator: ", ")
                            if !cityState.isEmpty { parts.append(cityState) }
                            if !residence.postalCode.isEmpty { parts.append(residence.postalCode) }
                            return parts.joined(separator: " ")
                        }())
                            .font(.system(size: 14, weight: .medium))
                            .foregroundColor(Color.appTextSecondary)
                    }
                }

                if !residence.country.isEmpty {
                    HStack(spacing: 10) {
                        Color.clear.frame(width: 32, height: 1) // Alignment spacer

                        Text(residence.country)
                            .font(.system(size: 13, weight: .medium))
                            .foregroundColor(Color.appTextSecondary.opacity(0.8))
                    }
                }
            }
            .padding(.horizontal, OrganicSpacing.cozy)
            .padding(.vertical, 16)

            // Property Details (if available)
            if let bedrooms = residence.bedrooms, let bathrooms = residence.bathrooms {
                OrganicDivider()
                    .padding(.horizontal, 20)

                // Property Features Row
                HStack(spacing: 0) {
                    PropertyFeaturePill(
                        icon: "bed.double.fill",
                        value: "\(bedrooms.intValue)",
                        label: "Beds"
                    )

                    PropertyFeaturePill(
                        icon: "shower.fill",
                        value: String(format: "%.1f", bathrooms.doubleValue),
                        label: "Baths"
                    )

                    if let sqft = residence.squareFootage {
                        PropertyFeaturePill(
                            icon: "square.dashed",
                            value: formatNumber(sqft.intValue),
                            label: "Sq Ft"
                        )
                    }

                    if let yearBuilt = residence.yearBuilt {
                        PropertyFeaturePill(
                            icon: "calendar",
                            value: "\(yearBuilt.intValue)",
                            label: "Built"
                        )
                    }
                }
                .padding(.horizontal, 12)
                .padding(.vertical, 16)
                .accessibilityElement(children: .combine)
            }
        }
        .background(PropertyHeaderBackground())
        .clipShape(RoundedRectangle(cornerRadius: 32, style: .continuous))
        .naturalShadow(.pronounced)
    }

    private static let decimalFormatter: NumberFormatter = {
        let formatter = NumberFormatter()
        formatter.numberStyle = .decimal
        return formatter
    }()

    private func formatNumber(_ num: Int) -> String {
        Self.decimalFormatter.string(from: NSNumber(value: num)) ?? "\(num)"
    }
}

// MARK: - Property Detail Icon

private struct PropertyDetailIcon: View {
    var body: some View {
        ZStack {
            // Outer glow
            Circle()
                .fill(
                    RadialGradient(
                        colors: [
                            Color.appPrimary.opacity(0.15),
                            Color.appPrimary.opacity(0.05)
                        ],
                        center: .center,
                        startRadius: 0,
                        endRadius: 32
                    )
                )
                .frame(width: 64, height: 64)

            // Inner circle
            Circle()
                .fill(
                    RadialGradient(
                        colors: [
                            Color.appPrimary,
                            Color.appPrimary.opacity(0.9)
                        ],
                        center: .topLeading,
                        startRadius: 0,
                        endRadius: 48
                    )
                )
                .frame(width: 48, height: 48)

            // Highlight
            Circle()
                .fill(
                    RadialGradient(
                        colors: [
                            Color.white.opacity(0.3),
                            Color.clear
                        ],
                        center: .topLeading,
                        startRadius: 0,
                        endRadius: 24
                    )
                )
                .frame(width: 48, height: 48)

            // Icon
            Image("outline")
                .resizable()
                .scaledToFit()
                .frame(width: 22, height: 22)
                .foregroundColor(Color.appTextOnPrimary)
        }
        .naturalShadow(.subtle)
        .a11yDecorative()
    }
}

// MARK: - Property Feature Pill

private struct PropertyFeaturePill: View {
    let icon: String
    let value: String
    let label: String

    var body: some View {
        VStack(spacing: 6) {
            HStack(spacing: 6) {
                Image(systemName: icon)
                    .font(.system(size: 12, weight: .semibold))
                    .foregroundColor(Color.appPrimary)

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

            Text(label)
                .font(.system(size: 11, weight: .medium))
                .foregroundColor(Color.appTextSecondary)
        }
        .frame(minWidth: 0, maxWidth: .infinity)
        .frame(height: 48)
    }
}

// MARK: - Property Header Background

private struct PropertyHeaderBackground: View {
    @Environment(\.colorScheme) var colorScheme

    var body: some View {
        ZStack {
            // Base
            Color.appBackgroundSecondary

            // Decorative blob
            GeometryReader { geo in
                OrganicBlobShape(variation: 0)
                    .fill(
                        RadialGradient(
                            colors: [
                                Color.appPrimary.opacity(colorScheme == .dark ? 0.08 : 0.05),
                                Color.appPrimary.opacity(0.01)
                            ],
                            center: .center,
                            startRadius: 0,
                            endRadius: geo.size.width * 0.4
                        )
                    )
                    .frame(width: geo.size.width * 0.6, height: geo.size.height * 0.7)
                    .offset(x: geo.size.width * 0.5, y: -geo.size.height * 0.1)
                    .blur(radius: 25)
            }

            // Grain texture
            GrainTexture(opacity: 0.012)
        }
    }
}

// MARK: - Preview

#Preview("Property Header Card") {
    ScrollView {
        VStack(spacing: 24) {
            PropertyHeaderCard(residence: ResidenceResponse(
                id: 1,
                ownerId: 1,
                owner: ResidenceUserResponse(id: 1, username: "testuser", email: "test@test.com", firstName: "John", lastName: "Doe"),
                users: [],
                name: "Sunset Villa",
                propertyTypeId: 1,
                propertyType: ResidenceType(id: 1, name: "House"),
                streetAddress: "742 Evergreen Terrace",
                apartmentUnit: "",
                city: "San Francisco",
                stateProvince: "CA",
                postalCode: "94102",
                country: "USA",
                bedrooms: 4,
                bathrooms: 2.5,
                squareFootage: 2400,
                lotSize: 0.35,
                yearBuilt: 2018,
                description: "Beautiful modern home with stunning views",
                purchaseDate: nil,
                purchasePrice: nil,
                isPrimary: true,
                isActive: true,
                overdueCount: 0,
                completionSummary: nil,
                heatingType: nil,
                coolingType: nil,
                waterHeaterType: nil,
                roofType: nil,
                hasPool: false,
                hasSprinklerSystem: false,
                hasSeptic: false,
                hasFireplace: false,
                hasGarage: false,
                hasBasement: false,
                hasAttic: false,
                exteriorType: nil,
                flooringPrimary: nil,
                landscapingType: nil,
                createdAt: "2024-01-01T00:00:00Z",
                updatedAt: "2024-01-01T00:00:00Z"
            ))
        }
        .padding(.horizontal, 16)
        .padding(.vertical, 24)
    }
    .background(WarmGradientBackground())
}
