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 isPurchasing = false
    @State private var isRestoring = false

    private let features: [(icon: String, title: String, subtitle: String)] = [
        ("brain.head.profile",   "KI-Analyse",           "Muster, Beziehungsqualität & konkrete Empfehlungen per KI"),
        ("gift.fill",            "Geschenkideen",        "KI-basierte Vorschläge bei bevorstehenden Geburtstagen"),
        ("square.and.arrow.up",  "Messenger-Import",     "Nachrichten aus WhatsApp, Telegram & Co. direkt ins Logbuch"),
        ("paintpalette.fill",    "Alle Themes",          "Grove, Ink, Copper, Abyss, Dusk & Basalt"),
        ("sparkles",             "Neurodivers-Themes",   "Reizarme Designs mit reduzierter Bewegung"),
        ("star.fill",            "Zukünftige Features",  "Alle kommenden Pro-Features inklusive"),
    ]

    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: 32) {

                        // Header
                        VStack(spacing: 8) {
                            Image("AppLogo")
                                .resizable()
                                .frame(width: 72, height: 72)
                                .clipShape(RoundedRectangle(cornerRadius: 16, style: .continuous))
                                .padding(.top, 24)

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

                            Text("Hol das Beste aus nahbar heraus.")
                                .font(.system(size: 15))
                                .foregroundStyle(theme.contentSecondary)
                                .multilineTextAlignment(.center)
                        }

                        // Features
                        VStack(spacing: 0) {
                            ForEach(features.indices, id: \.self) { i in
                                if i > 0 { RowDivider() }
                                featureRow(features[i])
                            }
                        }
                        .background(theme.surfaceCard)
                        .clipShape(RoundedRectangle(cornerRadius: theme.radiusCard))
                        .padding(.horizontal, 20)

                        // Price + CTA
                        VStack(spacing: 12) {
                            Button {
                                Task {
                                    isPurchasing = true
                                    await store.purchase()
                                    isPurchasing = false
                                    if store.isPro { dismiss() }
                                }
                            } label: {
                                HStack(spacing: 8) {
                                    if isPurchasing {
                                        ProgressView()
                                            .tint(.white)
                                    } else {
                                        Text(priceLabel)
                                            .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 { 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)
                            }
                        }

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

    private var priceLabel: String {
        if let product = store.product {
            return "\(product.displayPrice) / \(periodLabel(product)) abonnieren"
        }
        return "Abonnieren"
    }

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

    private func featureRow(_ feature: (icon: String, title: String, subtitle: 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())

            VStack(alignment: .leading, spacing: 2) {
                Text(feature.title)
                    .font(.system(size: 15, weight: .medium))
                    .foregroundStyle(theme.contentPrimary)
                Text(feature.subtitle)
                    .font(.system(size: 12))
                    .foregroundStyle(theme.contentTertiary)
            }
            Spacer()
        }
        .padding(.horizontal, 16)
        .padding(.vertical, 12)
    }
}
