import StoreKit
import SwiftUI
import AppKit

struct PremiumFeaturesView: View {
    /// When presented from AppKit (`NSWindow.beginSheet`), use this to dismiss; SwiftUI `dismiss` may not close the sheet.
    var onDismissFromAppKitHost: (() -> Void)? = nil

    enum PlanOption: String {
        case perpetual
        case yearly

        fileprivate var productID: PremiumProductID {
            switch self {
            case .perpetual: return .perpetual
            case .yearly: return .yearly
            }
        }
    }

    @EnvironmentObject private var premiumStore: PremiumStore
    @Environment(\.dismiss) private var dismiss
    @Environment(\.colorScheme) private var colorScheme
    @State private var selectedPlan: PlanOption = .perpetual
    @State private var showingSuccessAlert = false
    
    private enum ExternalPage {
        static let terms = "https://sites.google.com/view/apps-launcher/terms-of-service"
        static let privacy = "https://sites.google.com/view/apps-launcher/privacy-policy"
        static let support = "https://sites.google.com/view/apps-launcher/support"
    }

    private let featureRows: [(String, String)] = [
        ("Desktop Widgets", "Add and manage app widgets directly on your desktop"),
        ("Custom Web Apps", "Create your own app shortcuts with any website URL"),
        ("Status Bar Shortcuts", "Pin selected apps to the menu bar for one-click access"),
        ("Desktop Shortcuts", "Generate .webloc shortcuts directly to your Desktop"),
        ("Quick Actions", "Open common app actions faster from widget and panel controls"),
        ("Gesture Mode", "Use browser swipe gestures for quick back and forward navigation"),
        ("Always on Top Pin", "Keep important app windows floating above other windows"),
        ("Downloads Access", "Open your Downloads folder quickly from the in-app browser"),
        ("App Organization", "Pin, reorder, hide, and restore apps from your launcher view"),
        ("Family Sharing", "Allow eligible purchases to be shared with family members"),
    ]

    private let cardColors: [Color] = [
        .blue, .purple, .red, .green, .orange,
        .indigo, .pink, .cyan, .gray, .mint,
    ]

    private var selectedProduct: Product? {
        premiumStore.product(for: selectedPlan.productID)
    }

    private func priceLine(for plan: PlanOption) -> String {
        if let p = premiumStore.displayPrice(for: plan.productID) {
            return p
        }
        if premiumStore.isLoadingProducts {
            return "Loading…"
        }
        return "—"
    }

    var body: some View {
        ZStack {
            LinearGradient(
                colors: backgroundGradientColors,
                startPoint: .topLeading,
                endPoint: .bottomTrailing
            )
            .ignoresSafeArea()

            ScrollView {
                VStack(alignment: .leading, spacing: 14) {
                    HStack {
                        Button(action: { dismissPremiumUI() }) {
                            Image(systemName: "xmark")
                                .font(.system(size: 13, weight: .semibold))
                                .foregroundStyle(primaryTextColor)
                        }
                        .buttonStyle(.plain)

                        Spacer()

                        Button {
                            Task { await premiumStore.restorePurchases() }
                        } label: {
                            HStack(spacing: 6) {
                                if premiumStore.restoreInProgress {
                                    ProgressView()
                                        .controlSize(.mini)
                                }
                                Text(premiumStore.restoreInProgress ? "Restoring..." : "Restore")
                                    .font(.system(size: 11, weight: .semibold))
                            }
                            .foregroundStyle(primaryTextColor)
                            .padding(.horizontal, 8)
                            .padding(.vertical, 3)
                            .background(
                                RoundedRectangle(cornerRadius: 7, style: .continuous)
                                    .fill(chipFillColor)
                            )
                        }
                        .buttonStyle(.plain)
                        .disabled(premiumStore.purchaseInProgress || premiumStore.restoreInProgress)
                    }

                    Text("Upgrade to unlock all Premium Features")
                        .font(.system(size: 20, weight: .bold))
                        .foregroundStyle(primaryTextColor)
                        .lineSpacing(1)

                    if let err = premiumStore.loadError {
                        Text(err)
                            .font(.system(size: 11, weight: .medium))
                            .foregroundStyle(.orange.opacity(0.95))
                    }

                    if let err = premiumStore.purchaseError {
                        Text(err)
                            .font(.system(size: 11, weight: .medium))
                            .foregroundStyle(.orange.opacity(0.95))
                    }

                    if let restoreMessage = premiumStore.restoreMessage {
                        Text(restoreMessage)
                            .font(.system(size: 11, weight: .medium))
                            .foregroundStyle(.green.opacity(0.95))
                    }

                    LazyVGrid(
                        columns: [GridItem(.flexible(), spacing: 10), GridItem(.flexible(), spacing: 10)],
                        spacing: 10
                    ) {
                        ForEach(Array(featureRows.enumerated()), id: \.offset) { index, feature in
                            featureCard(title: feature.0, subtitle: feature.1, color: cardColors[index % cardColors.count])
                        }
                    }

                    if productsUnavailable {
                        VStack(alignment: .leading, spacing: 10) {
                            Text("Store products not loaded")
                                .font(.system(size: 14, weight: .bold))
                                .foregroundStyle(primaryTextColor)
                            Text(
                                "Prices and checkout need product metadata from App Store Connect, or a StoreKit Configuration file when running from Xcode. Product IDs must match exactly."
                            )
                            .font(.system(size: 11, weight: .medium))
                            .foregroundStyle(secondaryTextColor)
                            .fixedSize(horizontal: false, vertical: true)
                            Button {
                                Task { await premiumStore.loadProducts() }
                            } label: {
                                Text("Retry")
                                    .font(.system(size: 13, weight: .semibold))
                                    .foregroundStyle(.white)
                                    .frame(maxWidth: .infinity)
                                    .padding(.vertical, 10)
                                    .background(RoundedRectangle(cornerRadius: 10, style: .continuous).fill(Color.orange.opacity(0.85)))
                            }
                            .buttonStyle(.plain)
                        }
                        .padding(14)
                        .frame(maxWidth: .infinity, alignment: .leading)
                        .background(
                            RoundedRectangle(cornerRadius: 14, style: .continuous)
                                .fill(Color.orange.opacity(0.18))
                        )
                        .overlay(
                            RoundedRectangle(cornerRadius: 14, style: .continuous)
                                .stroke(Color.orange.opacity(0.45), lineWidth: 1)
                        )
                    }

                    priceCard(
                        title: "Lifetime",
                        price: priceLine(for: .perpetual),
                        subtitle: "Own the software for lifetime",
                        badgeText: "One-time payment",
                        isSelected: selectedPlan == .perpetual
                    )
                    .onTapGesture {
                        selectedPlan = .perpetual
                    }

                    priceCard(
                        title: "Yearly",
                        price: priceLine(for: .yearly),
                        subtitle: "Billed annually",
                        badgeText: nil,
                        isSelected: selectedPlan == .yearly
                    )
                    .onTapGesture {
                        selectedPlan = .yearly
                    }

                    Button(action: {
                        guard let product = selectedProduct else { return }
                        Task {
                            let ok = await premiumStore.purchase(product)
                            if ok {
                                showingSuccessAlert = true
                            }
                        }
                    }) {
                        HStack {
                            if premiumStore.purchaseInProgress {
                                ProgressView()
                                    .controlSize(.small)
                                    .tint(.white)
                            }
                            Text("Continue")
                                .font(.system(size: 16, weight: .bold))
                        }
                        .foregroundStyle(.white)
                        .frame(maxWidth: .infinity)
                        .padding(.vertical, 12)
                        .background(
                            RoundedRectangle(cornerRadius: 16, style: .continuous)
                                .fill(continueEnabled ? Color.blue.opacity(0.9) : Color.gray.opacity(0.55))
                        )
                    }
                    .buttonStyle(.plain)
                    .disabled(!continueEnabled)
                    .padding(.top, 6)

                    HStack {
                        Spacer()
                        Button("Privacy Policy") {
                            openExternalPage(ExternalPage.privacy)
                        }
                        .buttonStyle(.plain)
                        .font(.system(size: 11, weight: .medium))
                        .foregroundStyle(secondaryTextColor)
                        
                        Spacer()
                        
                        Button("Support") {
                            openExternalPage(ExternalPage.support)
                        }
                        .buttonStyle(.plain)
                        .font(.system(size: 11, weight: .medium))
                        .foregroundStyle(secondaryTextColor)
                        
                        Spacer()
                        
                        Button("Terms of Service") {
                            openExternalPage(ExternalPage.terms)
                        }
                        .buttonStyle(.plain)
                        .font(.system(size: 11, weight: .medium))
                        .foregroundStyle(secondaryTextColor)
                        Spacer()
                    }
                    .padding(.top, 2)
                }
                .padding(16)
            }
        }
        .task {
            await premiumStore.loadProducts()
        }
        .alert("Payment Successful", isPresented: $showingSuccessAlert) {
            Button("Done") { dismissPremiumUI() }
        } message: {
            Text("Your \(selectedPlan == .perpetual ? "Lifetime" : "Yearly") plan has been activated.")
        }
    }

    private var productsUnavailable: Bool {
        premiumStore.products.isEmpty && !premiumStore.isLoadingProducts
    }

    private var continueEnabled: Bool {
        selectedProduct != nil && !premiumStore.purchaseInProgress && !premiumStore.isLoadingProducts
    }

    private func dismissPremiumUI() {
        if let onDismissFromAppKitHost {
            onDismissFromAppKitHost()
        } else {
            dismiss()
        }
    }
    
    private func openExternalPage(_ urlString: String) {
        guard let url = URL(string: urlString) else { return }
        _ = NSWorkspace.shared.open(url)
    }

    private var backgroundGradientColors: [Color] {
        if colorScheme == .dark {
            return [Color.black.opacity(0.9), Color(red: 0.08, green: 0.1, blue: 0.14)]
        }
        return [Color.white.opacity(0.96), Color(red: 0.92, green: 0.95, blue: 1.0)]
    }

    private var primaryTextColor: Color {
        colorScheme == .dark ? .white.opacity(0.92) : .primary.opacity(0.95)
    }

    private var secondaryTextColor: Color {
        colorScheme == .dark ? .white.opacity(0.72) : .primary.opacity(0.70)
    }

    private var chipFillColor: Color {
        colorScheme == .dark ? .white.opacity(0.16) : .black.opacity(0.08)
    }

    private func featureCard(title: String, subtitle: String, color: Color) -> some View {
        HStack(alignment: .top, spacing: 10) {
            Circle()
                .fill(color.opacity(0.95))
                .frame(width: 28, height: 28)
                .overlay(
                    Image(systemName: "sparkles")
                        .font(.system(size: 11, weight: .semibold))
                        .foregroundStyle(.white)
                )

            VStack(alignment: .leading, spacing: 3) {
                Text(title)
                    .font(.system(size: 11.5, weight: .bold))
                    .foregroundStyle(primaryTextColor)
                    .lineLimit(1)
                Text(subtitle)
                    .font(.system(size: 9.5, weight: .medium))
                    .foregroundStyle(secondaryTextColor)
                    .lineLimit(2)
            }
            Spacer(minLength: 0)
        }
        .padding(10)
        .frame(maxWidth: .infinity, minHeight: 66, alignment: .leading)
        .background(
            RoundedRectangle(cornerRadius: 12, style: .continuous)
                .fill(colorScheme == .dark ? Color.white.opacity(0.14) : Color.black.opacity(0.05))
        )
    }

    private func priceCard(title: String, price: String, subtitle: String, badgeText: String?, isSelected: Bool) -> some View {
        let cardStroke: Color = {
            if isSelected { return Color.blue.opacity(0.95) }
            return colorScheme == .dark ? Color.white.opacity(0.4) : Color.black.opacity(0.18)
        }()
        let cardFill: Color = {
            if isSelected { return Color.blue.opacity(colorScheme == .dark ? 0.12 : 0.10) }
            return colorScheme == .dark ? Color.white.opacity(0.05) : Color.black.opacity(0.025)
        }()
        let cardStrokeWidth: CGFloat = isSelected ? 2 : 1.5

        return HStack(alignment: .center) {
            VStack(alignment: .leading, spacing: 5) {
                Text(title)
                    .font(.system(size: 12, weight: .bold))
                    .foregroundStyle(primaryTextColor)
                Text(subtitle)
                    .font(.system(size: 7.5, weight: .medium))
                    .foregroundStyle(secondaryTextColor)
            }

            Spacer()

            VStack(alignment: .trailing, spacing: 7) {
                Text(price)
                    .font(.system(size: 10, weight: .bold))
                    .foregroundStyle(primaryTextColor)
                    .minimumScaleFactor(0.7)
                    .lineLimit(1)
                if let badgeText {
                    Text(badgeText)
                        .font(.system(size: 7.5, weight: .bold))
                        .foregroundStyle(.white)
                        .padding(.horizontal, 8)
                        .padding(.vertical, 4)
                        .background(
                            RoundedRectangle(cornerRadius: 7, style: .continuous)
                                .fill(Color.blue.opacity(0.95))
                        )
                }
            }
        }
        .padding(10)
        .background(
            RoundedRectangle(cornerRadius: 14, style: .continuous)
                .stroke(cardStroke, lineWidth: cardStrokeWidth)
                .background(
                    RoundedRectangle(cornerRadius: 14, style: .continuous)
                        .fill(cardFill)
                )
        )
        .contentShape(RoundedRectangle(cornerRadius: 14, style: .continuous))
    }
}

#if DEBUG
#Preview {
    PremiumFeaturesView()
        .environmentObject(PremiumStore.shared)
        .frame(width: 560, height: 690)
}
#endif
