import SwiftUI
import StoreKit

// MARK: - SupportNudgeSheet

/// Modal sheet that surfaces the donation options and encourages the user
/// to support active development. Shown at most every 6 months.
struct SupportNudgeSheet: View {
    @Binding var isPresented: Bool
    @State private var service = DonationService.shared

    var body: some View {
        VStack(spacing: 0) {
            ScrollView {
                VStack(spacing: 28) {
                    headerIcon
                        .padding(.top, 40)

                    textBlock

                    productList

                    Button {
                        isPresented = false
                    } label: {
                        Text(L("nudge.dismiss"))
                            .font(.subheadline)
                            .foregroundStyle(.secondary)
                            .padding(.vertical, 8)
                    }
                    .padding(.bottom, 32)
                }
                .padding(.horizontal, 24)
            }
        }
        .task { await service.loadProducts() }
        .onChange(of: service.purchaseState) { _, state in
            // Auto-close after the thank-you moment
            if case .thankYou = state {
                Task {
                    try? await Task.sleep(for: .seconds(2))
                    isPresented = false
                }
            }
        }
    }

    // MARK: - Subviews

    private var headerIcon: some View {
        ZStack {
            Circle()
                .fill(
                    LinearGradient(
                        colors: [Color.pink.opacity(0.18), Color.orange.opacity(0.12)],
                        startPoint: .topLeading,
                        endPoint: .bottomTrailing
                    )
                )
                .frame(width: 112, height: 112)
            Image(systemName: "heart.fill")
                .font(.system(size: 50))
                .foregroundStyle(
                    LinearGradient(
                        colors: [.pink, .orange],
                        startPoint: .topLeading,
                        endPoint: .bottomTrailing
                    )
                )
        }
    }

    private var textBlock: some View {
        VStack(spacing: 10) {
            Text(L("nudge.title"))
                .font(.title2.bold())
                .multilineTextAlignment(.center)
            Text(L("nudge.subtitle"))
                .font(.body)
                .foregroundStyle(.secondary)
                .multilineTextAlignment(.center)
                .lineSpacing(2)
        }
    }

    @ViewBuilder
    private var productList: some View {
        switch service.loadState {
        case .loading:
            HStack {
                Text(L("settings.donate.loading"))
                    .foregroundStyle(.secondary)
                    .font(.subheadline)
                Spacer()
                ProgressView().controlSize(.small)
            }
            .padding()
            .background(Color(.secondarySystemBackground), in: RoundedRectangle(cornerRadius: 14))

        case .loaded(let products):
            VStack(spacing: 8) {
                ForEach(products, id: \.id) { product in
                    NudgeProductRow(product: product, service: service)
                }
            }

        case .empty, .failed:
            EmptyView()
        }
    }
}

// MARK: - NudgeProductRow

private struct NudgeProductRow: View {
    let product: Product
    let service: DonationService

    private var isPurchasing: Bool { service.purchaseState.activePurchasingID == product.id }
    private var isThankYou: Bool  { service.purchaseState.thankYouID == product.id }
    private var isDisabled: Bool  { service.purchaseState.activePurchasingID != nil }

    var body: some View {
        Button {
            guard !isDisabled else { return }
            Task { await service.purchase(product) }
        } label: {
            HStack(spacing: 14) {
                VStack(alignment: .leading, spacing: 3) {
                    Text(product.displayName)
                        .font(.body.weight(.medium))
                        .foregroundStyle(.primary)
                    Text(product.description)
                        .font(.caption)
                        .foregroundStyle(.secondary)
                        .lineLimit(1)
                }
                Spacer()
                trailingView
            }
            .padding(14)
            .background(Color(.secondarySystemBackground), in: RoundedRectangle(cornerRadius: 12))
        }
        .buttonStyle(.plain)
        .disabled(isDisabled)
    }

    @ViewBuilder
    private var trailingView: some View {
        if isPurchasing {
            ProgressView().controlSize(.small)
        } else if isThankYou {
            Image(systemName: "heart.fill")
                .foregroundStyle(.pink)
        } else {
            Text(product.displayPrice)
                .font(.subheadline.bold())
                .monospacedDigit()
                .foregroundStyle(
                    LinearGradient(colors: [.pink, .orange], startPoint: .leading, endPoint: .trailing)
                )
        }
    }
}

// MARK: - SupporterBadge

/// Inline badge shown in Settings for users who have donated.
struct SupporterBadgeRow: View {
    var body: some View {
        HStack(spacing: 14) {
            ZStack {
                Circle()
                    .fill(
                        LinearGradient(
                            colors: [.pink, .orange],
                            startPoint: .topLeading,
                            endPoint: .bottomTrailing
                        )
                    )
                    .frame(width: 42, height: 42)
                Image(systemName: "heart.fill")
                    .font(.system(size: 19))
                    .foregroundStyle(.white)
            }
            VStack(alignment: .leading, spacing: 2) {
                Text(L("supporter.badge.title"))
                    .font(.body.bold())
                    .foregroundStyle(.primary)
                Text(L("supporter.badge.subtitle"))
                    .font(.caption)
                    .foregroundStyle(.secondary)
            }
            Spacer()
        }
        .padding(.vertical, 4)
    }
}
