//
//  SettingsView.swift
//  BusinessCard
//
//  App settings screen using Bedrock settings layout contract:
//  SettingsCard owns horizontal inset, custom rows use SettingsCardRow,
//  and in-card separators use SettingsDivider.
//

import SwiftUI
import Bedrock

struct SettingsView: View {
    @Environment(AppState.self) private var appState
    @Environment(\.openURL) private var openURL
    @State private var settingsState = SettingsState()
    @State private var showingResetOnboardingConfirmation = false
    private let appName = BundleAppMetadataProvider().appName
    
    var body: some View {
        NavigationStack {
            ScrollView {
                VStack(spacing: Design.Spacing.large) {
                    
                    // MARK: - Settings Sections
                    appearanceSection
                    cardsSection
                    sharingSection
                    contactsSection
                    supportSection
                    
                    // MARK: - Debug Section
                    
                    #if DEBUG
                    debugSection
                    #endif
                    
                    Spacer(minLength: Design.Spacing.xxxLarge)
                }
                .padding(.horizontal, Design.Spacing.large)
                .padding(.top, Design.Spacing.medium)
            }
            .background(Color.AppBackground.base)
            .safeAreaInset(edge: .bottom) {
                versionFooter
            }
            .navigationTitle(String.localized("Settings"))
            .navigationBarTitleDisplayMode(.large)
            .alert("Reset Onboarding", isPresented: $showingResetOnboardingConfirmation) {
                Button("Cancel", role: .cancel) { }
                Button("Reset", role: .destructive) {
                    appState.preferences.hasCompletedOnboarding = false
                }
            } message: {
                Text("Onboarding will be shown again the next time you open the app.")
            }
        }
    }

    // MARK: - Appearance Section

    private var appearanceSection: some View {
        VStack(alignment: .leading, spacing: Design.Spacing.small) {
            SettingsSectionHeader(
                title: "Appearance",
                systemImage: "paintbrush",
                accentColor: AppThemeAccent.primary
            )

            SettingsCard(
                backgroundColor: Color.AppBackground.elevated,
                borderColor: AppBorder.standard
            ) {
                SettingsSegmentedPicker(
                    title: "Theme",
                    subtitle: "Choose app theme",
                    options: [
                        ("System", AppAppearance.system),
                        ("Light", AppAppearance.light),
                        ("Dark", AppAppearance.dark)
                    ],
                    selection: Binding(
                        get: { appState.preferences.appearance },
                        set: { appState.preferences.appearance = $0 }
                    ),
                    accentColor: AppThemeAccent.primary
                )
            }
        }
    }

    private var versionFooter: some View {
        Text(settingsState.versionString)
            .typography(.caption)
            .fontDesign(.monospaced)
            .foregroundStyle(Color.AppText.secondary)
            .frame(maxWidth: .infinity)
            .padding(.vertical, Design.Spacing.small)
            .background(Color.AppBackground.base)
    }

    // MARK: - Cards Section

    private var cardsSection: some View {
        VStack(alignment: .leading, spacing: Design.Spacing.small) {
            SettingsSectionHeader(
                title: "Cards",
                systemImage: "rectangle.stack",
                accentColor: AppThemeAccent.primary
            )

            SettingsCard(
                backgroundColor: Color.AppBackground.elevated,
                borderColor: AppBorder.standard
            ) {
                if appState.cardStore.cards.isEmpty {
                    SettingsCardRow {
                        HStack {
                            Text("Default Card")
                                .typography(.bodyEmphasis)
                                .foregroundStyle(Color.AppText.primary)

                            Spacer()

                            Text("Create a card first")
                                .typography(.body)
                                .foregroundStyle(Color.AppText.secondary)
                        }
                    }
                } else {
                    SettingsNavigationRow(
                        title: "Default Card",
                        subtitle: defaultCardTitle,
                        backgroundColor: .clear
                    ) {
                        DefaultCardSelectionView()
                    }
                }
            }
        }
    }

    // MARK: - Sharing Section

    private var sharingSection: some View {
        VStack(alignment: .leading, spacing: Design.Spacing.small) {
            SettingsSectionHeader(
                title: "Sharing",
                systemImage: "square.and.arrow.up",
                accentColor: AppThemeAccent.primary
            )

            SettingsCard(
                backgroundColor: Color.AppBackground.elevated,
                borderColor: AppBorder.standard
            ) {
                SettingsSegmentedPicker(
                    title: "Preferred Share Action",
                    subtitle: "Prioritize this option in Send Your Card",
                    options: PreferredShareAction.allCases.map { ($0.localizedTitle, $0) },
                    selection: Binding(
                        get: { appState.appSettings.preferredShareAction },
                        set: { appState.appSettings.preferredShareAction = $0 }
                    ),
                    accentColor: AppThemeAccent.primary
                )
            }
        }
    }

    // MARK: - Contacts Section

    private var contactsSection: some View {
        VStack(alignment: .leading, spacing: Design.Spacing.small) {
            SettingsSectionHeader(
                title: "Contacts",
                systemImage: "person.2",
                accentColor: AppThemeAccent.primary
            )

            SettingsCard(
                backgroundColor: Color.AppBackground.elevated,
                borderColor: AppBorder.standard
            ) {
                SettingsSegmentedPicker(
                    title: "Default Follow-Up",
                    subtitle: "Apply to newly created contacts",
                    options: DefaultFollowUpPreset.allCases.map { ($0.localizedTitle, $0) },
                    selection: Binding(
                        get: { appState.appSettings.defaultFollowUpPreset },
                        set: { appState.appSettings.defaultFollowUpPreset = $0 }
                    ),
                    accentColor: AppThemeAccent.primary
                )
            }
        }
    }

    // MARK: - Support Section

    private var supportSection: some View {
        VStack(alignment: .leading, spacing: Design.Spacing.small) {
            SettingsSectionHeader(
                title: "Support",
                systemImage: "questionmark.circle",
                accentColor: AppThemeAccent.primary
            )

            SettingsCard(
                backgroundColor: Color.AppBackground.elevated,
                borderColor: AppBorder.standard
            ) {
                supportRow(
                    title: "Send Feedback",
                    subtitle: "Email support"
                ) {
                    let subject = "\(appName) Support".addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed) ?? "Support"
                    guard let url = URL(string: "mailto:info@topdoglabs.com?subject=\(subject)") else { return }
                    openURL(url)
                }

                SettingsDivider(color: AppBorder.subtle)

                supportRow(
                    title: "Privacy Policy",
                    subtitle: "How we handle data"
                ) {
                    guard let url = URL(string: "https://topdoglabs.com/privacy") else { return }
                    openURL(url)
                }

                SettingsDivider(color: AppBorder.subtle)

                supportRow(
                    title: "Website",
                    subtitle: "topdoglabs.com"
                ) {
                    guard let url = URL(string: "https://topdoglabs.com") else { return }
                    openURL(url)
                }
            }
        }
    }

    private var defaultCardTitle: String {
        if let defaultCard = appState.cardStore.cards.first(where: { $0.isDefault }) {
            return displayTitle(for: defaultCard)
        }
        if let selectedCard = appState.cardStore.selectedCard {
            return displayTitle(for: selectedCard)
        }
        return "Not set"
    }

    private func displayTitle(for card: BusinessCard) -> String {
        let trimmedName = card.fullName.trimmingCharacters(in: .whitespacesAndNewlines)
        if !trimmedName.isEmpty {
            return trimmedName
        }
        let trimmedLabel = card.label.trimmingCharacters(in: .whitespacesAndNewlines)
        if !trimmedLabel.isEmpty {
            return trimmedLabel
        }
        return "Untitled"
    }

    @ViewBuilder
    private func supportRow(title: String, subtitle: String, action: @escaping () -> Void) -> some View {
        SettingsCardRow {
            Button(action: action) {
                HStack {
                    VStack(alignment: .leading, spacing: Design.Spacing.xxxSmall) {
                        Text(title)
                            .typography(.bodyEmphasis)
                            .foregroundStyle(Color.AppText.primary)

                        Text(subtitle)
                            .typography(.caption)
                            .foregroundStyle(Color.AppText.secondary)
                    }

                    Spacer()

                    Image(systemName: "arrow.up.right.square")
                        .typography(.subheading)
                        .foregroundStyle(Color.AppText.secondary)
                }
            }
            .buttonStyle(.plain)
        }
    }
    
    // MARK: - Debug Section
    
    #if DEBUG
    private var debugSection: some View {
        VStack(alignment: .leading, spacing: Design.Spacing.small) {
            SettingsSectionHeader(
                title: "Debug",
                systemImage: "ant.fill",
                accentColor: AppStatus.error
            )
            
            SettingsCard(
                backgroundColor: Color.AppBackground.elevated,
                borderColor: AppBorder.standard
            ) {
                SettingsToggle(
                    title: "Enable Debug Premium",
                    subtitle: "Unlock all premium features for testing",
                    isOn: Binding(
                        get: { appState.preferences.isDebugPremiumEnabled },
                        set: { appState.preferences.isDebugPremiumEnabled = $0 }
                    ),
                    accentColor: AppStatus.warning
                )

                SettingsDivider(color: AppBorder.subtle)

                SettingsCardRow {
                    Button {
                        showingResetOnboardingConfirmation = true
                    } label: {
                        HStack {
                            VStack(alignment: .leading, spacing: Design.Spacing.xxxSmall) {
                                Text("Reset Onboarding")
                                    .typography(.bodyEmphasis)
                                    .foregroundStyle(AppStatus.error)

                                Text("Show first-run onboarding again on next app launch")
                                    .typography(.caption)
                                    .foregroundStyle(Color.AppText.secondary)
                            }

                            Spacer()

                            Image(systemName: "arrow.counterclockwise")
                                .typography(.subheading)
                                .foregroundStyle(AppStatus.error)
                        }
                    }
                    .buttonStyle(.plain)
                }

                SettingsDivider(color: AppBorder.subtle)

                SettingsNavigationRow(
                    title: "Icon Generator",
                    subtitle: "Generate and save app icon to Files",
                    backgroundColor: .clear
                ) {
                    IconGeneratorView(config: .businessCard, appName: appName)
                }

                SettingsDivider(color: AppBorder.subtle)

                SettingsNavigationRow(
                    title: "Branding Preview",
                    subtitle: "Preview app icon and launch screen",
                    backgroundColor: .clear
                ) {
                    BrandingPreviewView(
                        iconConfig: .businessCard,
                        launchConfig: .businessCard,
                        appName: appName
                    )
                }
            }
        }
    }
    #endif
}

// MARK: - Preview

#Preview {
    SettingsView()
}
