import SwiftUI
import StoreKit

struct PaywallView: View {
    @Environment(\.nahbarTheme) private var theme
    @Environment(\.dismiss) private var dismiss
    @StateObject private var store = StoreManager.shared

    @State private var selectedTier: SubscriptionTier
    @State private var isPurchasing = false
    @State private var isRestoring = false

    init(targeting tier: SubscriptionTier = .pro) {
        _selectedTier = State(initialValue: tier)
    }

    // MARK: - Feature-Definitionen

    private let proFeatures: [(icon: String, text: String)] = [
        ("person.badge.plus",       "Unbegrenzte Kontakte statt 3"),
        ("square.and.arrow.up",     "Teilen-Funktion: Momente aus anderen Apps importieren"),
        ("paintpalette.fill",       "Alle Themes: Grove, Ink, Copper, Abyss, Dusk & Basalt"),
        ("sparkles",                "Neurodivers-Themes: reizarme Designs"),
        ("star.fill",               "Alle zukünftigen Pro-Features inklusive"),
    ]

    private let maxExtraFeatures: [(icon: String, text: String)] = [
        ("brain.head.profile",      "KI-Analyse: Muster, Beziehungsqualität & Empfehlungen"),
        ("gift.fill",               "Geschenkideen: KI-Vorschläge bei Geburtstagen"),
        ("text.bubble.fill",        "Gesprächsthemen vorschlagen: KI-Impulse für bessere Treffen"),
        ("infinity",                "Unbegrenzte KI-Abfragen ohne Limit"),
    ]

    // MARK: - Body

    var body: some View {
        ZStack {
            theme.backgroundPrimary.ignoresSafeArea()

            VStack(spacing: 0) {
                // Handle
                Capsule()
                    .fill(theme.borderSubtle)
                    .frame(width: 36, height: 4)
                    .padding(.top, 12)

                ScrollView {
                    VStack(spacing: 28) {
                        // Header
                        header

                        // Tier-Picker
                        tierPicker

                        // Features
                        featureList

                        // CTA
                        ctaSection

                        // Legal
                        Text("Abonnement verlängert sich automatisch. In den iPhone-Einstellungen jederzeit kündbar.")
                            .font(.system(size: 11))
                            .foregroundStyle(theme.contentTertiary)
                            .multilineTextAlignment(.center)
                            .padding(.horizontal, 32)
                            .padding(.bottom, 32)
                    }
                }
            }
        }
    }

    // MARK: - Subviews

    private var header: some View {
        VStack(spacing: 8) {
            Image("AppLogo")
                .resizable()
                .frame(width: 72, height: 72)
                .clipShape(RoundedRectangle(cornerRadius: 16, style: .continuous))
                .padding(.top, 24)

            Text("nahbar")
                .font(.system(size: 26, weight: .light, design: theme.displayDesign))
                .foregroundStyle(theme.contentPrimary)

            Text("Wähle deinen Plan")
                .font(.system(size: 15))
                .foregroundStyle(theme.contentSecondary)
        }
    }

    private var tierPicker: some View {
        HStack(spacing: 0) {
            ForEach(SubscriptionTier.allCases, id: \.productID) { tier in
                Button {
                    withAnimation(.easeInOut(duration: 0.2)) { selectedTier = tier }
                } label: {
                    VStack(spacing: 4) {
                        Text(tier.displayName)
                            .font(.system(size: 15, weight: selectedTier == tier ? .semibold : .regular))
                            .foregroundStyle(selectedTier == tier ? theme.accent : theme.contentSecondary)
                        if tier == .max {
                            Text("inkl. KI")
                                .font(.system(size: 10, weight: .medium))
                                .foregroundStyle(selectedTier == .max ? theme.accent : theme.contentTertiary)
                        } else {
                            Text("Basis")
                                .font(.system(size: 10))
                                .foregroundStyle(theme.contentTertiary)
                        }
                    }
                    .frame(maxWidth: .infinity)
                    .padding(.vertical, 12)
                    .background(
                        selectedTier == tier
                            ? theme.accent.opacity(0.10)
                            : theme.surfaceCard
                    )
                }
            }
        }
        .clipShape(RoundedRectangle(cornerRadius: theme.radiusCard))
        .overlay(
            RoundedRectangle(cornerRadius: theme.radiusCard)
                .strokeBorder(theme.borderSubtle, lineWidth: 1)
        )
        .padding(.horizontal, 20)
    }

    @ViewBuilder
    private var featureList: some View {
        VStack(spacing: 0) {
            if selectedTier == .max {
                // Max: Pro-Features als Paket + Max-Extras einzeln
                proPackageRow
                ForEach(maxExtraFeatures.indices, id: \.self) { i in
                    RowDivider()
                    featureRow(maxExtraFeatures[i])
                }
            } else {
                // Pro: alle Pro-Features einzeln
                ForEach(proFeatures.indices, id: \.self) { i in
                    if i > 0 { RowDivider() }
                    featureRow(proFeatures[i])
                }
            }
        }
        .background(theme.surfaceCard)
        .clipShape(RoundedRectangle(cornerRadius: theme.radiusCard))
        .padding(.horizontal, 20)
    }

    private var proPackageRow: some View {
        HStack(spacing: 14) {
            Image(systemName: "checkmark.seal.fill")
                .font(.system(size: 15))
                .foregroundStyle(theme.accent)
                .frame(width: 32, height: 32)
                .background(theme.accent.opacity(0.10))
                .clipShape(Circle())

            VStack(alignment: .leading, spacing: 2) {
                Text("Alles aus Pro")
                    .font(.system(size: 15, weight: .medium))
                    .foregroundStyle(theme.contentPrimary)
                Text("Kontakte, Teilen-Funktion, Themes")
                    .font(.system(size: 12))
                    .foregroundStyle(theme.contentTertiary)
            }
            Spacer()
        }
        .padding(.horizontal, 16)
        .padding(.vertical, 12)
    }

    private func featureRow(_ feature: (icon: String, text: String)) -> some View {
        HStack(spacing: 14) {
            Image(systemName: feature.icon)
                .font(.system(size: 15))
                .foregroundStyle(theme.accent)
                .frame(width: 32, height: 32)
                .background(theme.accent.opacity(0.10))
                .clipShape(Circle())

            Text(feature.text)
                .font(.system(size: 14))
                .foregroundStyle(theme.contentPrimary)
                .fixedSize(horizontal: false, vertical: true)

            Spacer()
        }
        .padding(.horizontal, 16)
        .padding(.vertical, 12)
    }

    private var ctaSection: some View {
        VStack(spacing: 12) {
            Button {
                Task {
                    isPurchasing = true
                    await store.purchase(tier: selectedTier)
                    isPurchasing = false
                    let didSucceed = selectedTier == .max ? store.isMax : store.isPro
                    if didSucceed { dismiss() }
                }
            } label: {
                HStack(spacing: 8) {
                    if isPurchasing {
                        ProgressView().tint(.white)
                    } else {
                        Text(ctaLabel)
                            .font(.system(size: 17, weight: .semibold))
                    }
                }
                .frame(maxWidth: .infinity)
                .frame(height: 52)
                .background(theme.accent)
                .foregroundStyle(.white)
                .clipShape(RoundedRectangle(cornerRadius: theme.radiusCard))
            }
            .disabled(isPurchasing || isRestoring)
            .padding(.horizontal, 20)

            Button {
                Task {
                    isRestoring = true
                    await store.restorePurchases()
                    isRestoring = false
                    if store.isPro || store.isMax { dismiss() }
                }
            } label: {
                if isRestoring {
                    ProgressView().tint(theme.contentTertiary)
                } else {
                    Text("Kauf wiederherstellen")
                        .font(.system(size: 14))
                        .foregroundStyle(theme.contentTertiary)
                }
            }
            .disabled(isPurchasing || isRestoring)

            if let error = store.purchaseError {
                Text(error)
                    .font(.system(size: 12))
                    .foregroundStyle(.red.opacity(0.8))
                    .multilineTextAlignment(.center)
                    .padding(.horizontal, 20)
            }
        }
    }

    // MARK: - Hilfsmethoden

    private var ctaLabel: String {
        let product = selectedTier == .pro ? store.proProduct : store.maxProduct
        let price = product.map { "\($0.displayPrice) / \(periodLabel($0))" } ?? ""
        let action = selectedTier == .max && store.isPro
            ? String(localized: "Zu Max upgraden")
            : String.localizedStringWithFormat(String(localized: "%@ freischalten"), selectedTier.displayName)
        return price.isEmpty ? action : "\(price) – \(action)"
    }

    private func periodLabel(_ product: Product) -> String {
        guard let sub = product.subscription else { return String(localized: "Monat") }
        switch sub.subscriptionPeriod.unit {
        case .day:   return sub.subscriptionPeriod.value == 7 ? String(localized: "Woche") : String(localized: "Tag")
        case .week:  return String(localized: "Woche")
        case .month: return String(localized: "Monat")
        case .year:  return String(localized: "Jahr")
        @unknown default: return String(localized: "Zeitraum")
        }
    }
}
