import SwiftUI

// MARK: - Theme Picker View

struct ThemePickerView: View {
    @Environment(\.nahbarTheme) var theme
    @AppStorage("activeThemeID") private var activeThemeIDRaw: String = ThemeID.linen.rawValue
    @StateObject private var store = StoreManager.shared

    @State private var previewID: ThemeID = .linen
    @State private var showPaywall = false

    private var activeThemeID: ThemeID {
        ThemeID(rawValue: activeThemeIDRaw) ?? .linen
    }

    private var lightThemes: [ThemeID] {
        ThemeID.allCases.filter { !$0.isDark }
    }

    private var darkThemes: [ThemeID] {
        ThemeID.allCases.filter { $0.isDark && !$0.isNeurodiverseFocused }
    }

    private var ndThemes: [ThemeID] {
        ThemeID.allCases.filter { $0.isNeurodiverseFocused }
    }

    var body: some View {
        ScrollView {
            VStack(alignment: .leading, spacing: 28) {

                // Live Preview
                ThemePreviewCard(previewTheme: NahbarTheme.theme(for: previewID))
                    .padding(.horizontal, 20)
                    .padding(.top, 4)
                    .animation(.easeInOut(duration: 0.25), value: previewID)

                // Hell
                themeGroup(title: "Hell", icon: "sun.max", themes: lightThemes)

                // Dunkel
                themeGroup(title: "Dunkel", icon: "moon", themes: darkThemes)

                // Neurodivers
                VStack(alignment: .leading, spacing: 10) {
                    VStack(alignment: .leading, spacing: 2) {
                        SectionHeader(title: "Neurodivers", icon: "sparkles")
                            .padding(.horizontal, 20)
                        Text("Dunkel · Reizarm · Reduzierte Bewegung")
                            .font(.system(size: 12))
                            .foregroundStyle(theme.contentTertiary)
                            .padding(.horizontal, 20)
                    }
                    VStack(spacing: 8) {
                        ForEach(ndThemes, id: \.self) { id in
                            themeRow(id: id)
                        }
                    }
                    .padding(.horizontal, 20)
                }
            }
            .padding(.bottom, 40)
        }
        .background(theme.backgroundPrimary.ignoresSafeArea())
        .navigationTitle("Atmosphäre")
        .navigationBarTitleDisplayMode(.inline)
        .themedNavBar()
        .onAppear {
            previewID = activeThemeID
        }
        .sheet(isPresented: $showPaywall) {
            PaywallView()
        }
    }

    // MARK: - Group

    private func themeGroup(title: LocalizedStringKey, icon: String, themes: [ThemeID]) -> some View {
        VStack(alignment: .leading, spacing: 10) {
            SectionHeader(title: title, icon: icon)
                .padding(.horizontal, 20)
            VStack(spacing: 8) {
                ForEach(themes, id: \.self) { id in
                    themeRow(id: id)
                }
            }
            .padding(.horizontal, 20)
        }
    }

    // MARK: - Row

    private func themeRow(id: ThemeID) -> some View {
        let preview = NahbarTheme.theme(for: id)
        let isActive = id == activeThemeID
        let isPreviewing = id == previewID

        return Button {
            if id.isPremium && !store.isPro {
                showPaywall = true
            } else {
                previewID = id
                activeThemeIDRaw = id.rawValue
            }
        } label: {
            HStack(spacing: 14) {
                // Color swatch
                ZStack(alignment: .bottomTrailing) {
                    RoundedRectangle(cornerRadius: 8)
                        .fill(preview.backgroundPrimary)
                        .frame(width: 44, height: 44)
                        .overlay(
                            RoundedRectangle(cornerRadius: 8)
                                .stroke(isPreviewing ? theme.accent : theme.borderSubtle, lineWidth: isPreviewing ? 2 : 1)
                        )
                    RoundedRectangle(cornerRadius: 3)
                        .fill(preview.accent)
                        .frame(width: 14, height: 14)
                        .padding(3)
                }

                VStack(alignment: .leading, spacing: 2) {
                    Text(id.displayName)
                        .font(.system(size: 15, weight: isActive ? .semibold : .regular))
                        .foregroundStyle(theme.contentPrimary)
                    Text(id.tagline)
                        .font(.system(size: 12))
                        .foregroundStyle(theme.contentTertiary)
                }

                Spacer()

                if id.isPremium && !isActive {
                    ProBadge()
                }

                if isActive {
                    Image(systemName: "checkmark")
                        .font(.system(size: 13, weight: .semibold))
                        .foregroundStyle(theme.accent)
                }
            }
            .padding(.horizontal, 14)
            .padding(.vertical, 10)
            .background(theme.surfaceCard)
            .clipShape(RoundedRectangle(cornerRadius: theme.radiusCard))
        }
    }
}

// MARK: - Live Preview Card

struct ThemePreviewCard: View {
    let previewTheme: NahbarTheme

    var body: some View {
        ZStack(alignment: .topLeading) {
            RoundedRectangle(cornerRadius: 20)
                .fill(previewTheme.backgroundPrimary)
                .frame(height: 200)

            VStack(alignment: .leading, spacing: 0) {
                // Header
                VStack(alignment: .leading, spacing: 3) {
                    Text("Guten Morgen.")
                        .font(.system(size: 22, weight: .light, design: previewTheme.displayDesign))
                        .foregroundStyle(previewTheme.contentPrimary)
                    Text("Mittwoch, 16. April")
                        .font(.system(size: 12, design: previewTheme.displayDesign))
                        .foregroundStyle(previewTheme.contentTertiary)
                }
                .padding(.horizontal, 18)
                .padding(.top, 18)

                Spacer()

                // Mock card
                VStack(spacing: 0) {
                    mockRow(name: "Anna Müller", hint: "Heute Geburtstag 🎂", icon: "gift")
                    Rectangle()
                        .fill(previewTheme.borderSubtle)
                        .frame(height: 0.5)
                        .padding(.leading, 52)
                    mockRow(name: "Nächster Schritt", hint: "Meeting vorbereiten", icon: "arrow.right.circle")
                }
                .background(previewTheme.surfaceCard)
                .clipShape(RoundedRectangle(cornerRadius: previewTheme.radiusCard))
                .padding(.horizontal, 14)
                .padding(.bottom, 14)
            }

            // Accent bar
            HStack {
                Spacer()
                Capsule()
                    .fill(previewTheme.accent)
                    .frame(width: 36, height: 4)
                    .padding(.top, 12)
                    .padding(.trailing, 18)
            }
        }
        .frame(height: 200)
        .clipShape(RoundedRectangle(cornerRadius: 20))
        .shadow(color: Color.black.opacity(0.08), radius: 12, x: 0, y: 4)
    }

    private func mockRow(name: String, hint: String, icon: String) -> some View {
        HStack(spacing: 10) {
            Image(systemName: icon)
                .font(.system(size: 12))
                .foregroundStyle(previewTheme.accent)
                .frame(width: 28, height: 28)
                .background(previewTheme.accent.opacity(0.12))
                .clipShape(Circle())

            VStack(alignment: .leading, spacing: 1) {
                Text(name)
                    .font(.system(size: 12, weight: .medium, design: previewTheme.displayDesign))
                    .foregroundStyle(previewTheme.contentPrimary)
                Text(hint)
                    .font(.system(size: 10, design: previewTheme.displayDesign))
                    .foregroundStyle(previewTheme.contentSecondary)
            }
            Spacer()
        }
        .padding(.horizontal, 12)
        .padding(.vertical, 8)
    }
}
