import SwiftUI
import StoreKit

/// Screen 7: Subscription upsell - Content only (no navigation bar)
struct OnboardingSubscriptionContent: View {
    var onSubscribe: () -> Void

    @ObservedObject private var storeKit = StoreKitManager.shared
    @State private var isLoading = false
    @State private var purchaseError: String?
    @State private var selectedPlan: PricingPlan = .yearly
    @State private var animateBadge = false
    @Environment(\.colorScheme) var colorScheme

    private let benefits: [SubscriptionBenefit] = [
        SubscriptionBenefit(
            icon: "building.2.fill",
            title: "Unlimited Properties",
            description: "Track every home you own—vacation houses, rentals, you name it",
            gradient: [Color.appPrimary, Color.appSecondary]
        ),
        SubscriptionBenefit(
            icon: "doc.badge.plus",
            title: "Document Vault",
            description: "All your warranties, receipts, and manuals in one searchable place",
            gradient: [Color(hex: "#34C759") ?? .green, Color(hex: "#30D158") ?? .green]
        ),
        SubscriptionBenefit(
            icon: "person.3.fill",
            title: "Family Sharing",
            description: "Get everyone on the same page—literally",
            gradient: [Color(hex: "#AF52DE") ?? .purple, Color(hex: "#BF5AF2") ?? .purple]
        ),
        SubscriptionBenefit(
            icon: "square.and.arrow.up.fill",
            title: "Contractor Sharing",
            description: "Share your trusted contractors with family and friends",
            gradient: [Color.appAccent, Color(hex: "#FF9500") ?? .orange]
        ),
        SubscriptionBenefit(
            icon: "bell.badge.fill",
            title: "Actionable Notifications",
            description: "Complete tasks directly from notifications—no app opening needed",
            gradient: [Color(hex: "#FF3B30") ?? .red, Color(hex: "#FF6961") ?? .red]
        ),
        SubscriptionBenefit(
            icon: "square.grid.2x2.fill",
            title: "Home Screen Widgets",
            description: "Quick actions right from your home screen",
            gradient: [Color(hex: "#007AFF") ?? .blue, Color(hex: "#5AC8FA") ?? .blue]
        )
    ]

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

            // Decorative blobs
            GeometryReader { geo in
                OrganicBlobShape(variation: 0)
                    .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.3)
                    .offset(x: -geo.size.width * 0.15, y: geo.size.height * 0.05)
                    .blur(radius: 25)

                OrganicBlobShape(variation: 2)
                    .fill(
                        RadialGradient(
                            colors: [
                                Color.appPrimary.opacity(0.06),
                                Color.appPrimary.opacity(0.01),
                                Color.clear
                            ],
                            center: .center,
                            startRadius: 0,
                            endRadius: geo.size.width * 0.25
                        )
                    )
                    .frame(width: geo.size.width * 0.4, height: geo.size.height * 0.2)
                    .offset(x: geo.size.width * 0.65, y: geo.size.height * 0.7)
                    .blur(radius: 20)
            }
            .a11yDecorative()

            ScrollView(showsIndicators: false) {
                VStack(spacing: OrganicSpacing.comfortable) {
                    // Header with animated crown
                    VStack(spacing: 16) {
                        ZStack {
                            // Pulsing glow effect
                            Circle()
                                .fill(
                                    RadialGradient(
                                        colors: [Color.appAccent.opacity(0.25), Color.appAccent.opacity(0.05), Color.clear],
                                        center: .center,
                                        startRadius: 30,
                                        endRadius: 100
                                    )
                                )
                                .frame(width: 180, height: 180)
                                .scaleEffect(animateBadge ? 1.1 : 1.0)
                                .animation(
                                    animateBadge
                                        ? Animation.easeInOut(duration: 2).repeatForever(autoreverses: true)
                                        : .default,
                                    value: animateBadge
                                )

                            // Crown icon
                            ZStack {
                                Circle()
                                    .fill(
                                        LinearGradient(
                                            colors: [Color.appAccent, Color(hex: "#FF9500") ?? .orange],
                                            startPoint: .topLeading,
                                            endPoint: .bottomTrailing
                                        )
                                    )
                                    .frame(width: 100, height: 100)

                                Image(systemName: "crown.fill")
                                    .font(.system(size: 44))
                                    .foregroundColor(.white)
                            }
                            .naturalShadow(.pronounced)
                        }

                        // Pro badge
                        HStack(spacing: 6) {
                            Image(systemName: "sparkles")
                                .foregroundColor(Color.appAccent)
                            Text("HONEYDUE PRO")
                                .font(.system(size: 14, weight: .black))
                                .foregroundColor(Color.appAccent)
                            Image(systemName: "sparkles")
                                .foregroundColor(Color.appAccent)
                        }
                        .padding(.horizontal, 18)
                        .padding(.vertical, 10)
                        .background(
                            LinearGradient(
                                colors: [Color.appAccent.opacity(0.15), Color(hex: "#FF9500")?.opacity(0.15) ?? Color.orange.opacity(0.15)],
                                startPoint: .leading,
                                endPoint: .trailing
                            )
                        )
                        .clipShape(Capsule())

                        Text("Take your home management\nto the next level")
                            .font(.system(size: 22, weight: .bold, design: .rounded))
                            .foregroundColor(Color.appTextPrimary)
                            .multilineTextAlignment(.center)
                            .lineSpacing(4)

                        // Social proof
                        HStack(spacing: 6) {
                            ForEach(0..<5, id: \.self) { _ in
                                Image(systemName: "star.fill")
                                    .font(.system(size: 12))
                                    .foregroundColor(Color.appAccent)
                            }
                            Text("4.9")
                                .font(.system(size: 14, weight: .bold))
                                .foregroundColor(Color.appTextPrimary)
                            Text("• 10K+ homeowners")
                                .font(.system(size: 14, weight: .medium))
                                .foregroundColor(Color.appTextSecondary)
                        }
                        .accessibilityLabel("Rated 4.9 stars by 10K+ homeowners")
                    }
                    .padding(.top, OrganicSpacing.comfortable)

                    // Benefits list card
                    VStack(spacing: 10) {
                        ForEach(benefits) { benefit in
                            OrganicSubscriptionBenefitRow(benefit: benefit)
                        }
                    }
                    .padding(OrganicSpacing.cozy)
                    .background(
                        ZStack {
                            Color.appBackgroundSecondary

                            GeometryReader { geo in
                                OrganicBlobShape(variation: 1)
                                    .fill(Color.appAccent.opacity(colorScheme == .dark ? 0.06 : 0.04))
                                    .frame(width: geo.size.width * 0.4, height: geo.size.height * 0.5)
                                    .offset(x: geo.size.width * 0.65, y: geo.size.height * 0.3)
                                    .blur(radius: 20)
                            }

                            GrainTexture(opacity: 0.015)
                        }
                    )
                    .clipShape(RoundedRectangle(cornerRadius: 24, style: .continuous))
                    .naturalShadow(.medium)
                    .padding(.horizontal, 20)

                    // Pricing plans
                    VStack(spacing: 14) {
                        Text("Choose your plan")
                            .font(.system(size: 17, weight: .semibold))
                            .foregroundColor(Color.appTextPrimary)

                        // Yearly plan (best value)
                        OrganicPricingPlanCard(
                            plan: .yearly,
                            isSelected: selectedPlan == .yearly,
                            displayPrice: yearlyProduct()?.displayPrice,
                            onSelect: { selectedPlan = .yearly }
                        )

                        // Monthly plan
                        OrganicPricingPlanCard(
                            plan: .monthly,
                            isSelected: selectedPlan == .monthly,
                            displayPrice: monthlyProduct()?.displayPrice,
                            onSelect: { selectedPlan = .monthly }
                        )
                    }
                    .padding(.horizontal, 20)

                    // CTA buttons
                    VStack(spacing: 14) {
                        if let purchaseError = purchaseError {
                            HStack(spacing: 8) {
                                Image(systemName: "exclamationmark.circle.fill")
                                    .foregroundColor(Color.appError)
                                Text(purchaseError)
                                    .font(.system(size: 13, weight: .medium))
                                    .foregroundColor(Color.appError)
                            }
                            .frame(maxWidth: .infinity, alignment: .leading)
                            .padding(12)
                            .background(Color.appError.opacity(0.1))
                            .clipShape(RoundedRectangle(cornerRadius: 12, style: .continuous))
                        }

                        Button(action: startFreeTrial) {
                            HStack(spacing: 10) {
                                if isLoading {
                                    ProgressView()
                                        .progressViewStyle(CircularProgressViewStyle(tint: .white))
                                } else {
                                    Text("Start 7-Day Free Trial")
                                        .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.appAccent, Color(hex: "#FF9500") ?? .orange],
                                    startPoint: .leading,
                                    endPoint: .trailing
                                )
                            )
                            .clipShape(RoundedRectangle(cornerRadius: 16, style: .continuous))
                            .naturalShadow(.medium)
                        }
                        .disabled(isLoading)
                        .a11yButton("Start free trial")

                        // Continue without
                        Button(action: {
                            onSubscribe()
                        }) {
                            Text("Continue with Free")
                                .font(.system(size: 15, weight: .semibold))
                                .foregroundColor(Color.appTextSecondary)
                        }
                        .a11yButton("Continue with free plan")

                        // Legal text
                        VStack(spacing: 4) {
                            Text("7-day free trial, then \(productForSelectedPlan()?.displayPrice ?? selectedPlan.price)\(selectedPlan.period)")
                                .font(.system(size: 12, weight: .medium))
                                .foregroundColor(Color.appTextSecondary)

                            Text("Cancel anytime in Settings • No commitment")
                                .font(.system(size: 12, weight: .medium))
                                .foregroundColor(Color.appTextSecondary.opacity(0.7))
                        }
                        .multilineTextAlignment(.center)
                        .padding(.top, 4)
                    }
                    .padding(.horizontal, OrganicSpacing.comfortable)
                    .padding(.bottom, OrganicSpacing.airy)
                }
            }
        }
        .onAppear {
            animateBadge = true
        }
        .onDisappear {
            animateBadge = false
        }
        .task {
            if storeKit.products.isEmpty {
                await storeKit.loadProducts()
            }
        }
    }

    private func startFreeTrial() {
        isLoading = true
        purchaseError = nil

        // Initiate StoreKit purchase flow
        Task {
            do {
                if storeKit.products.isEmpty {
                    await storeKit.loadProducts()
                }

                guard let product = productForSelectedPlan() else {
                    throw StoreKitManager.StoreKitError.noProducts
                }

                let transaction = try await storeKit.purchase(product)

                await MainActor.run {
                    isLoading = false
                    if transaction != nil {
                        // Check if backend verification failed (purchase valid but pending server confirmation)
                        if let backendError = storeKit.purchaseError {
                            purchaseError = backendError
                        } else {
                            onSubscribe()
                        }
                    } else {
                        purchaseError = "Purchase was cancelled. You can continue with Free or try again."
                    }
                }
            } catch {
                await MainActor.run {
                    isLoading = false
                    purchaseError = "Unable to start trial: \(error.localizedDescription)"
                }
            }
        }
    }

    private func productForSelectedPlan() -> Product? {
        selectedPlan == .yearly ? yearlyProduct() : monthlyProduct()
    }

    private func yearlyProduct() -> Product? {
        storeKit.products.first { $0.id.localizedCaseInsensitiveContains("annual") }
            ?? storeKit.products.first
    }

    private func monthlyProduct() -> Product? {
        storeKit.products.first { $0.id.localizedCaseInsensitiveContains("monthly") }
            ?? storeKit.products.first
    }
}

// MARK: - Pricing Plan Enum

enum PricingPlan {
    case monthly
    case yearly

    var title: String {
        switch self {
        case .monthly: return "Monthly"
        case .yearly: return "Yearly"
        }
    }

    var price: String {
        switch self {
        case .monthly: return "$2.99"
        case .yearly: return "$23.99"
        }
    }

    var period: String {
        switch self {
        case .monthly: return "/month"
        case .yearly: return "/year"
        }
    }

    var monthlyEquivalent: String? {
        switch self {
        case .monthly: return nil
        case .yearly: return "Just $1.99/month"
        }
    }

    var savings: String? {
        switch self {
        case .monthly: return nil
        case .yearly: return "Save 30%"
        }
    }
}

// MARK: - Organic Pricing Plan Card

private struct OrganicPricingPlanCard: View {
    let plan: PricingPlan
    let isSelected: Bool
    var displayPrice: String? = nil
    var onSelect: () -> Void

    @Environment(\.colorScheme) var colorScheme

    var body: some View {
        Button(action: onSelect) {
            HStack {
                // Selection indicator
                ZStack {
                    Circle()
                        .stroke(isSelected ? Color.appAccent : Color.appTextSecondary.opacity(0.3), lineWidth: 2)
                        .frame(width: 24, height: 24)

                    if isSelected {
                        Circle()
                            .fill(Color.appAccent)
                            .frame(width: 14, height: 14)
                    }
                }

                VStack(alignment: .leading, spacing: 2) {
                    HStack(spacing: 8) {
                        Text(plan.title)
                            .font(.system(size: 16, weight: .semibold))
                            .foregroundColor(Color.appTextPrimary)

                        if let savings = plan.savings {
                            Text(savings)
                                .font(.system(size: 10, weight: .bold))
                                .foregroundColor(.white)
                                .padding(.horizontal, 8)
                                .padding(.vertical, 3)
                                .background(
                                    LinearGradient(
                                        colors: [Color(hex: "#34C759") ?? .green, Color(hex: "#30D158") ?? .green],
                                        startPoint: .leading,
                                        endPoint: .trailing
                                    )
                                )
                                .clipShape(Capsule())
                        }
                    }

                    if let monthlyEquivalent = plan.monthlyEquivalent {
                        Text(monthlyEquivalent)
                            .font(.system(size: 12, weight: .medium))
                            .foregroundColor(Color.appTextSecondary)
                    }
                }

                Spacer()

                VStack(alignment: .trailing, spacing: 0) {
                    Text(displayPrice ?? plan.price)
                        .font(.system(size: 20, weight: .bold))
                        .foregroundColor(isSelected ? Color.appAccent : Color.appTextPrimary)

                    Text(plan.period)
                        .font(.system(size: 12, weight: .medium))
                        .foregroundColor(Color.appTextSecondary)
                }
            }
            .padding(18)
            .background(
                ZStack {
                    Color.appBackgroundSecondary

                    if plan == .yearly {
                        GeometryReader { geo in
                            OrganicBlobShape(variation: 1)
                                .fill(Color.appAccent.opacity(colorScheme == .dark ? 0.06 : 0.04))
                                .frame(width: geo.size.width * 0.3, height: geo.size.height * 0.8)
                                .offset(x: geo.size.width * 0.75, y: 0)
                                .blur(radius: 10)
                        }
                    }

                    GrainTexture(opacity: 0.01)
                }
            )
            .clipShape(RoundedRectangle(cornerRadius: 18, style: .continuous))
            .overlay(
                RoundedRectangle(cornerRadius: 18, style: .continuous)
                    .stroke(
                        isSelected
                            ? LinearGradient(colors: [Color.appAccent, Color(hex: "#FF9500") ?? .orange], startPoint: .leading, endPoint: .trailing)
                            : LinearGradient(colors: [Color.appTextSecondary.opacity(0.2), Color.appTextSecondary.opacity(0.2)], startPoint: .leading, endPoint: .trailing),
                        lineWidth: isSelected ? 2 : 1
                    )
            )
            .naturalShadow(isSelected ? .medium : .subtle)
        }
        .buttonStyle(.plain)
        .animation(.easeInOut(duration: 0.2), value: isSelected)
        .accessibilityLabel("\(plan.title) plan, \(displayPrice ?? plan.price)\(plan.period)\(plan.savings.map { ", \($0)" } ?? "")")
        .accessibilityValue(isSelected ? "Selected" : "")
    }
}

// MARK: - Legacy wrapper with navigation bar (for backwards compatibility)

struct OnboardingSubscriptionView: View {
    var onSubscribe: () -> Void
    var onSkip: () -> Void

    var body: some View {
        OnboardingSubscriptionContent(onSubscribe: onSubscribe)
    }
}

// MARK: - Subscription Benefit Model

struct SubscriptionBenefit: Identifiable {
    let id = UUID()
    let icon: String
    let title: String
    let description: String
    let gradient: [Color]
}

// MARK: - Organic Subscription Benefit Row

private struct OrganicSubscriptionBenefitRow: View {
    let benefit: SubscriptionBenefit

    var body: some View {
        HStack(spacing: 14) {
            // Gradient icon
            ZStack {
                Circle()
                    .fill(
                        LinearGradient(
                            colors: benefit.gradient,
                            startPoint: .topLeading,
                            endPoint: .bottomTrailing
                        )
                    )
                    .frame(width: 40, height: 40)

                Image(systemName: benefit.icon)
                    .font(.system(size: 17, weight: .medium))
                    .foregroundColor(.white)
            }
            .naturalShadow(.subtle)
            .a11yDecorative()

            VStack(alignment: .leading, spacing: 2) {
                Text(benefit.title)
                    .font(.system(size: 14, weight: .semibold))
                    .foregroundColor(Color.appTextPrimary)

                Text(benefit.description)
                    .font(.system(size: 12, weight: .medium))
                    .foregroundColor(Color.appTextSecondary)
                    .lineLimit(2)
            }

            Spacer()

            Image(systemName: "checkmark")
                .font(.system(size: 12, weight: .bold))
                .foregroundColor(benefit.gradient[0])
                .a11yDecorative()
        }
        .padding(.horizontal, 4)
        .padding(.vertical, 6)
    }
}

// MARK: - Preview

#Preview {
    OnboardingSubscriptionContent(onSubscribe: {})
}
