import SwiftUI
import LocalAuthentication

struct SettingsView: View {
    @Environment(\.nahbarTheme) var theme
    @AppStorage("activeThemeID") private var activeThemeIDRaw: String = ThemeID.linen.rawValue
    @EnvironmentObject private var callWindowManager: CallWindowManager
    @EnvironmentObject private var appLockManager: AppLockManager

    @AppStorage("upcomingDaysAhead") private var daysAhead: Int = 7
    @AppStorage("icloudSyncEnabled") private var icloudSyncEnabled: Bool = false
    @AppStorage("aiBaseURL") private var aiBaseURL: String = AIConfig.fallback.baseURL
    @AppStorage("aiAPIKey")  private var aiAPIKey:  String = AIConfig.fallback.apiKey
    @AppStorage("aiModel")   private var aiModel:   String = AIConfig.fallback.model
    @StateObject private var store = StoreManager.shared
    @State private var showingPINSetup = false
    @State private var showingPINDisable = false
    @State private var showPaywall = false

    private var biometricLabel: String {
        switch appLockManager.biometricType {
        case .faceID:  return "Face ID aktiviert"
        case .touchID: return "Touch ID aktiviert"
        default:       return "Aktiv"
        }
    }

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

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

                    // Header
                    Text("Einstellungen")
                        .font(.system(size: 34, weight: .light, design: theme.displayDesign))
                        .foregroundStyle(theme.contentPrimary)
                        .padding(.horizontal, 20)
                        .padding(.top, 12)

                    // nahbar Pro (oben)
                    VStack(alignment: .leading, spacing: 12) {
                        SectionHeader(title: "nahbar Pro", icon: "star.fill")
                            .padding(.horizontal, 20)

                        if store.isPro {
                            HStack {
                                VStack(alignment: .leading, spacing: 2) {
                                    Text("Aktiv")
                                        .font(.system(size: 15))
                                        .foregroundStyle(theme.contentPrimary)
                                    Text("Alle Pro-Features freigeschaltet")
                                        .font(.system(size: 12))
                                        .foregroundStyle(theme.contentTertiary)
                                }
                                Spacer()
                                Image(systemName: "checkmark.seal.fill")
                                    .foregroundStyle(theme.accent)
                            }
                            .padding(.horizontal, 16)
                            .padding(.vertical, 12)
                            .background(theme.surfaceCard)
                            .clipShape(RoundedRectangle(cornerRadius: theme.radiusCard))
                            .padding(.horizontal, 20)
                        } else {
                            Button { showPaywall = true } label: {
                                HStack {
                                    VStack(alignment: .leading, spacing: 2) {
                                        Text("nahbar Pro entdecken")
                                            .font(.system(size: 15, weight: .medium))
                                            .foregroundStyle(theme.accent)
                                        Text("KI-Analyse, Themes & mehr")
                                            .font(.system(size: 12))
                                            .foregroundStyle(theme.contentTertiary)
                                    }
                                    Spacer()
                                    Image(systemName: "chevron.right")
                                        .font(.system(size: 12, weight: .medium))
                                        .foregroundStyle(theme.contentTertiary)
                                }
                                .padding(.horizontal, 16)
                                .padding(.vertical, 12)
                                .background(theme.surfaceCard)
                                .clipShape(RoundedRectangle(cornerRadius: theme.radiusCard))
                                .padding(.horizontal, 20)
                            }
                        }
                    }
                    .sheet(isPresented: $showPaywall) { PaywallView() }

                    // Theme picker
                    VStack(alignment: .leading, spacing: 12) {
                        SectionHeader(title: "Atmosphäre", icon: "paintpalette")
                            .padding(.horizontal, 20)

                        NavigationLink(destination: ThemePickerView()) {
                            HStack(spacing: 14) {
                                // Swatch
                                ZStack(alignment: .bottomTrailing) {
                                    RoundedRectangle(cornerRadius: 8)
                                        .fill(NahbarTheme.theme(for: activeThemeID).backgroundPrimary)
                                        .frame(width: 40, height: 40)
                                        .overlay(
                                            RoundedRectangle(cornerRadius: 8)
                                                .stroke(theme.borderSubtle, lineWidth: 1)
                                        )
                                    RoundedRectangle(cornerRadius: 3)
                                        .fill(NahbarTheme.theme(for: activeThemeID).accent)
                                        .frame(width: 13, height: 13)
                                        .padding(2)
                                }
                                VStack(alignment: .leading, spacing: 2) {
                                    Text(activeThemeID.displayName)
                                        .font(.system(size: 15, weight: .medium))
                                        .foregroundStyle(theme.contentPrimary)
                                    Text(activeThemeID.tagline)
                                        .font(.system(size: 12))
                                        .foregroundStyle(theme.contentTertiary)
                                }
                                Spacer()
                                Image(systemName: "chevron.right")
                                    .font(.system(size: 12, weight: .medium))
                                    .foregroundStyle(theme.contentTertiary)
                            }
                            .padding(.horizontal, 16)
                            .padding(.vertical, 12)
                            .background(theme.surfaceCard)
                            .clipShape(RoundedRectangle(cornerRadius: theme.radiusCard))
                            .padding(.horizontal, 20)
                        }
                    }

                    // App-Schutz
                    VStack(alignment: .leading, spacing: 12) {
                        SectionHeader(title: "App-Schutz", icon: "lock")
                            .padding(.horizontal, 20)

                        VStack(spacing: 0) {
                            HStack {
                                VStack(alignment: .leading, spacing: 2) {
                                    Text("Code-Schutz")
                                        .font(.system(size: 15))
                                        .foregroundStyle(theme.contentPrimary)
                                    if appLockManager.isEnabled {
                                        Text(biometricLabel)
                                            .font(.system(size: 12))
                                            .foregroundStyle(theme.contentTertiary)
                                    }
                                }
                                Spacer()
                                Toggle("", isOn: Binding(
                                    get: { appLockManager.isEnabled },
                                    set: { newValue in
                                        if newValue { showingPINSetup = true }
                                        else        { showingPINDisable = true }
                                    }
                                ))
                                .tint(theme.accent)
                            }
                            .padding(.horizontal, 16)
                            .padding(.vertical, 12)

                            if appLockManager.isEnabled {
                                RowDivider()
                                Button { showingPINSetup = true } label: {
                                    HStack {
                                        Text("Code ändern")
                                            .font(.system(size: 15))
                                            .foregroundStyle(theme.contentPrimary)
                                        Spacer()
                                        Image(systemName: "chevron.right")
                                            .font(.system(size: 12, weight: .medium))
                                            .foregroundStyle(theme.contentTertiary)
                                    }
                                    .padding(.horizontal, 16)
                                    .padding(.vertical, 12)
                                }
                            }
                        }
                        .background(theme.surfaceCard)
                        .clipShape(RoundedRectangle(cornerRadius: theme.radiusCard))
                        .padding(.horizontal, 20)
                    }
                    .sheet(isPresented: $showingPINSetup, onDismiss: { appLockManager.refreshBiometricType() }) {
                        AppLockSetupView(isDisabling: false)
                            .environmentObject(appLockManager)
                    }
                    .sheet(isPresented: $showingPINDisable) {
                        AppLockSetupView(isDisabling: true)
                            .environmentObject(appLockManager)
                    }

                    // Gesprächszeit
                    VStack(alignment: .leading, spacing: 12) {
                        SectionHeader(title: "Gesprächszeit", icon: "phone.arrow.up.right")
                            .padding(.horizontal, 20)

                        VStack(spacing: 0) {
                            HStack {
                                Text("Aktiv")
                                    .font(.system(size: 15))
                                    .foregroundStyle(theme.contentPrimary)
                                Spacer()
                                Toggle("", isOn: $callWindowManager.isEnabled)
                                    .tint(theme.accent)
                                    .onChange(of: callWindowManager.isEnabled) { _, enabled in
                                        if enabled {
                                            callWindowManager.scheduleNotifications()
                                        } else {
                                            callWindowManager.cancelNotifications()
                                        }
                                    }
                            }
                            .padding(.horizontal, 16)
                            .padding(.vertical, 12)

                            if callWindowManager.isEnabled {
                                RowDivider()
                                NavigationLink {
                                    CallWindowSetupView(
                                        manager: callWindowManager,
                                        isOnboarding: false,
                                        onDone: {}
                                    )
                                } label: {
                                    HStack {
                                        Text("Zeitfenster")
                                            .font(.system(size: 15))
                                            .foregroundStyle(theme.contentPrimary)
                                        Spacer()
                                        Text(callWindowManager.windowDescription)
                                            .font(.system(size: 14))
                                            .foregroundStyle(theme.contentTertiary)
                                        Image(systemName: "chevron.right")
                                            .font(.system(size: 12, weight: .medium))
                                            .foregroundStyle(theme.contentTertiary)
                                    }
                                    .padding(.horizontal, 16)
                                    .padding(.vertical, 12)
                                }
                            }
                        }
                        .background(theme.surfaceCard)
                        .clipShape(RoundedRectangle(cornerRadius: theme.radiusCard))
                        .padding(.horizontal, 20)
                    }

                    // Vorausschau
                    VStack(alignment: .leading, spacing: 12) {
                        SectionHeader(title: "Vorausschau", icon: "calendar")
                            .padding(.horizontal, 20)

                        VStack(spacing: 0) {
                            HStack {
                                Text("Geburtstage & Termine")
                                    .font(.system(size: 15))
                                    .foregroundStyle(theme.contentPrimary)
                                Spacer()
                                Picker("", selection: $daysAhead) {
                                    Text("3 Tage").tag(3)
                                    Text("1 Woche").tag(7)
                                    Text("2 Wochen").tag(14)
                                    Text("1 Monat").tag(30)
                                }
                                .tint(theme.accent)
                            }
                            .padding(.horizontal, 16)
                            .padding(.vertical, 8)
                        }
                        .background(theme.surfaceCard)
                        .clipShape(RoundedRectangle(cornerRadius: theme.radiusCard))
                        .padding(.horizontal, 20)
                    }

                    // KI-Einstellungen
                    VStack(alignment: .leading, spacing: 12) {
                        SectionHeader(title: "KI-Analyse", icon: "sparkles")
                            .padding(.horizontal, 20)

                        VStack(spacing: 0) {
                            settingsTextField(label: "Server-URL", value: $aiBaseURL, placeholder: AIConfig.fallback.baseURL)
                            RowDivider()
                            settingsTextField(label: "Modell", value: $aiModel, placeholder: AIConfig.fallback.model)
                        }
                        .background(theme.surfaceCard)
                        .clipShape(RoundedRectangle(cornerRadius: theme.radiusCard))
                        .padding(.horizontal, 20)
                    }

                    // iCloud
                    VStack(alignment: .leading, spacing: 12) {
                        SectionHeader(title: "iCloud", icon: "icloud")
                            .padding(.horizontal, 20)

                        VStack(spacing: 0) {
                            HStack {
                                VStack(alignment: .leading, spacing: 2) {
                                    Text("iCloud-Backup")
                                        .font(.system(size: 15))
                                        .foregroundStyle(theme.contentPrimary)
                                    Text(icloudSyncEnabled
                                         ? "Daten werden mit iCloud synchronisiert"
                                         : "Daten werden nur lokal gespeichert")
                                        .font(.system(size: 12))
                                        .foregroundStyle(theme.contentTertiary)
                                }
                                Spacer()
                                Toggle("", isOn: $icloudSyncEnabled)
                                    .tint(theme.accent)
                            }
                            .padding(.horizontal, 16)
                            .padding(.vertical, 12)

                            RowDivider()
                            HStack(spacing: 8) {
                                Image(systemName: "info.circle")
                                    .font(.system(size: 12))
                                    .foregroundStyle(theme.contentTertiary)
                                Text("Änderung wird beim nächsten App-Start übernommen.")
                                    .font(.system(size: 12))
                                    .foregroundStyle(theme.contentTertiary)
                            }
                            .padding(.horizontal, 16)
                            .padding(.vertical, 10)
                        }
                        .background(theme.surfaceCard)
                        .clipShape(RoundedRectangle(cornerRadius: theme.radiusCard))
                        .padding(.horizontal, 20)
                    }

                    // About
                    VStack(alignment: .leading, spacing: 12) {
                        SectionHeader(title: "Über nahbar", icon: "info.circle")
                            .padding(.horizontal, 20)

                        VStack(spacing: 0) {
                            SettingsInfoRow(label: "Version", value: "1.0 Draft")
                            RowDivider()
                            SettingsInfoRow(label: "Datenschutz", value: "Deine Daten verlassen nicht dein Gerät")
                        }
                        .background(theme.surfaceCard)
                        .clipShape(RoundedRectangle(cornerRadius: theme.radiusCard))
                        .padding(.horizontal, 20)
                    }
                }
                .padding(.bottom, 40)
            }
            .background(theme.backgroundPrimary.ignoresSafeArea())
            .navigationBarHidden(true)
        }
    }
}

// MARK: - Settings TextField Helper

extension SettingsView {
    func settingsTextField(label: String, value: Binding<String>, placeholder: String) -> some View {
        HStack {
            Text(label)
                .font(.system(size: 15))
                .foregroundStyle(theme.contentPrimary)
                .frame(width: 90, alignment: .leading)
            TextField(placeholder, text: value)
                .font(.system(size: 14))
                .foregroundStyle(theme.contentSecondary)
                .autocorrectionDisabled()
                .textInputAutocapitalization(.never)
                .multilineTextAlignment(.trailing)
        }
        .padding(.horizontal, 16)
        .padding(.vertical, 12)
    }
}

// MARK: - Theme Option Row

struct ThemeOptionRow: View {
    @Environment(\.nahbarTheme) var current
    let themeID: ThemeID
    let isActive: Bool
    let onSelect: () -> Void

    private var preview: NahbarTheme { NahbarTheme.theme(for: themeID) }

    var body: some View {
        Button(action: onSelect) {
            HStack(spacing: 14) {
                // Color swatch
                HStack(spacing: 3) {
                    RoundedRectangle(cornerRadius: 5)
                        .fill(preview.backgroundPrimary)
                        .frame(width: 32, height: 32)
                        .overlay(
                            RoundedRectangle(cornerRadius: 5)
                                .stroke(current.borderSubtle, lineWidth: 1)
                        )
                    RoundedRectangle(cornerRadius: 3)
                        .fill(preview.accent)
                        .frame(width: 10, height: 32)
                }

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

                Spacer()

                if themeID.isPremium {
                    Text("PRO")
                        .font(.system(size: 10, weight: .bold))
                        .foregroundStyle(current.accent)
                        .padding(.horizontal, 7)
                        .padding(.vertical, 3)
                        .background(current.accent.opacity(0.10))
                        .clipShape(Capsule())
                }

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

// MARK: - Settings Info Row

struct SettingsInfoRow: View {
    @Environment(\.nahbarTheme) var theme
    let label: String
    let value: String

    var body: some View {
        HStack(alignment: .top) {
            Text(label)
                .font(.system(size: 15))
                .foregroundStyle(theme.contentPrimary)
            Spacer()
            Text(value)
                .font(.system(size: 14))
                .foregroundStyle(theme.contentTertiary)
                .multilineTextAlignment(.trailing)
        }
        .padding(.horizontal, 16)
        .padding(.vertical, 12)
    }
}
