import SwiftUI
import Bedrock
import MijickCamera
import RevenueCatUI

struct SettingsView: View {
    @Bindable var viewModel: SettingsViewModel
    @Binding var showPaywall: Bool
    @Environment(\.dismiss) private var dismiss
    
    /// Whether to show RevenueCat Customer Center
    @State private var showCustomerCenter = false
    
    /// Whether premium features are unlocked (for UI gating)
    private var isPremiumUnlocked: Bool {
        viewModel.isPremiumUnlocked
    }
    
    /// Shows paywall after dismissing settings
    private func showPaywallAfterDismiss() {
        dismiss()
        DispatchQueue.main.asyncAfter(deadline: .now() + 0.3) {
            showPaywall = true
        }
    }

    
    var body: some View {
        NavigationStack {
            ScrollView {
                VStack(spacing: Design.Spacing.medium) {

                    // MARK: - Ring Light Section

                    SettingsSectionHeader(title: "Ring Light", systemImage: "light.max", accentColor: AppAccent.primary)
                    
                    SettingsCard(backgroundColor: AppSurface.card, borderColor: AppBorder.subtle) {
                        // Ring Light Enabled
                        SettingsToggle(
                            title: String(localized: "Enable Ring Light"),
                            subtitle: String(localized: "Show colored light ring around camera preview"),
                            isOn: $viewModel.isRingLightEnabled,
                            accentColor: AppAccent.primary
                        )
                        .accessibilityHint(String(localized: "Enables or disables the ring light overlay"))

                        // Ring Size Slider
                        ringSizeSlider

                        // Color Preset
                        colorPresetSection

                        // Ring Light Brightness
                        ringLightBrightnessSlider
                    }

                    // MARK: - Camera Controls Section

                    SettingsSectionHeader(title: "Camera Controls", systemImage: "camera", accentColor: AppAccent.primary)
                    
                    SettingsCard(backgroundColor: AppSurface.card, borderColor: AppBorder.subtle) {
                        // Camera Position
                        cameraPositionPicker

                        // Flash Mode
                        flashModePicker

                        // Flash Sync (premium)
                        premiumToggle(
                            title: String(localized: "Flash Sync"),
                            subtitle: String(localized: "Use ring light color for screen flash"),
                            isOn: $viewModel.isFlashSyncedWithRingLight,
                            accessibilityHint: String(localized: "Syncs flash color with ring light color")
                        )

                        // HDR Mode
                        hdrModePicker

                        // Center Stage (premium feature)
                        premiumToggle(
                            title: String(localized: "Center Stage"),
                            subtitle: String(localized: "Automatically keeps you centered in the frame"),
                            isOn: $viewModel.isCenterStageEnabled,
                            accessibilityHint: String(localized: "Automatically adjusts camera to keep subject centered")
                        )

                        // Photo Quality
                        photoQualityPicker
                    }

                    // MARK: - Display Section

                    SettingsSectionHeader(title: "Display", systemImage: "eye", accentColor: AppAccent.primary)
                    
                    SettingsCard(backgroundColor: AppSurface.card, borderColor: AppBorder.subtle) {
                        
                        SettingsToggle(
                            title: String(localized: "Grid Overlay"),
                            subtitle: String(localized: "Shows rule of thirds grid for composition"),
                            isOn: $viewModel.isGridVisible,
                            accentColor: AppAccent.primary
                        )
                        .accessibilityHint(String(localized: "Shows a grid overlay to help compose your shot"))

                        // True Mirror (premium)
                        premiumToggle(
                            title: String(localized: "True Mirror"),
                            subtitle: String(localized: "Shows horizontally flipped preview like a real mirror"),
                            isOn: $viewModel.isMirrorFlipped,
                            accessibilityHint: String(localized: "Flips the camera preview horizontally")
                        )

                        // Skin Smoothing (premium)
                        premiumToggle(
                            title: String(localized: "Skin Smoothing"),
                            subtitle: String(localized: "Applies subtle real-time skin smoothing"),
                            isOn: $viewModel.isSkinSmoothingEnabled,
                            accessibilityHint: String(localized: "Applies light skin smoothing to the camera preview")
                        )
                    }

                    // MARK: - Capture Section

                    SettingsSectionHeader(title: "Capture", systemImage: "photo.on.rectangle", accentColor: AppAccent.primary)
                    
                    SettingsCard(backgroundColor: AppSurface.card, borderColor: AppBorder.subtle) {

                        SettingsToggle(
                            title: String(localized: "Auto-Save"),
                            subtitle: String(localized: "Automatically save captures to Photo Library"),
                            isOn: $viewModel.isAutoSaveEnabled,
                            accentColor: AppAccent.primary
                        )
                        .accessibilityHint(String(localized: "When enabled, photos and videos are saved immediately after capture"))
                        
                        // Timer Selection
                        timerPicker

                    }

                    // MARK: - Pro Section

                    SettingsSectionHeader(title: "Pro", systemImage: "crown", accentColor: AppStatus.warning)

                    proSection

                    // MARK: - Sync Section

                    SettingsSectionHeader(title: String(localized: "iCloud Sync"), systemImage: "icloud", accentColor: AppAccent.primary)
                    
                    SettingsCard(backgroundColor: AppSurface.card, borderColor: AppBorder.subtle) {
                        iCloudSyncSection
                    }

                    // MARK: - About Section

                    SettingsSectionHeader(title: "About", systemImage: "info.circle", accentColor: AppAccent.primary)
                    
                    SettingsCard(backgroundColor: AppSurface.card, borderColor: AppBorder.subtle) {
                        acknowledgmentsSection
                    }
                    
                    // MARK: - Debug Section
                    
                    #if DEBUG
                    SettingsSectionHeader(title: "Debug", systemImage: "ant.fill", accentColor: AppStatus.error)
                    
                    SettingsCard(backgroundColor: AppSurface.card, borderColor: AppBorder.subtle) {
                        brandingDebugSection
                    }
                    #endif
                    
                    Spacer(minLength: Design.Spacing.xxxLarge)
                }
                .padding(.horizontal, Design.Spacing.large)
            }
            .background(AppSurface.primary)
            .navigationTitle(String(localized: "Settings"))
            .navigationBarTitleDisplayMode(.inline)
            .toolbar {
                ToolbarItem(placement: .topBarTrailing) {
                    Button(String(localized: "Done")) {
                        dismiss()
                    }
                    .foregroundStyle(AppAccent.primary)
                }
            }
        }
    }
    
    // MARK: - Ring Size Slider

    private var ringSizeSlider: some View {
        SettingsSlider(
            title: String(localized: "Ring Size"),
            subtitle: String(localized: "Adjusts the size of the light ring around the camera preview"),
            value: $viewModel.ringSize,
            in: SettingsViewModel.minRingSize...SettingsViewModel.maxRingSize,
            step: 5,
            format: SliderFormat.integer(unit: "pt"),
            accentColor: AppAccent.primary,
            leadingIcon: Image(systemName: "circle"),
            trailingIcon: Image(systemName: "circle")
        )
        .accessibilityLabel(String(localized: "Ring size"))
        .accessibilityValue("\(Int(viewModel.ringSize)) points")
    }
    
    // MARK: - Color Preset Section

    private var colorPresetSection: some View {
        VStack(alignment: .leading, spacing: Design.Spacing.small) {
            Text(String(localized: "Light Color"))
                .font(.system(size: Design.FontSize.medium, weight: .medium))
                .foregroundStyle(.white)

            Text(String(localized: "Choose the color of the ring light around the camera preview"))
                .font(.system(size: Design.FontSize.caption))
                .foregroundStyle(.white.opacity(Design.Opacity.medium))

            LazyVGrid(
                columns: [GridItem(.adaptive(minimum: 80), spacing: Design.Spacing.small)],
                spacing: Design.Spacing.small
            ) {
                // Preset colors
                ForEach(RingLightColor.allPresets) { preset in
                    ColorPresetButton(
                        preset: preset,
                        isSelected: viewModel.selectedLightColor == preset,
                        isPremiumUnlocked: isPremiumUnlocked
                    ) {
                        // Premium colors require unlock
                        if preset.isPremium && !isPremiumUnlocked {
                            dismiss()
                            DispatchQueue.main.asyncAfter(deadline: .now() + 0.3) {
                                showPaywall = true
                            }
                        } else {
                            viewModel.selectedLightColor = preset
                        }
                    }
                }

                // Custom color picker (premium) - one-step: opens picker, selects on change
                CustomColorPickerButton(
                    customColor: Binding(
                        get: { viewModel.customColor },
                        set: { viewModel.selectCustomColor($0) }
                    ),
                    isSelected: viewModel.isCustomColorSelected,
                    isPremiumUnlocked: isPremiumUnlocked,
                    onPremiumRequired: {
                        dismiss()
                        DispatchQueue.main.asyncAfter(deadline: .now() + 0.3) {
                            showPaywall = true
                        }
                    }
                )
            }
        }
        .padding(.vertical, Design.Spacing.xSmall)
    }
    
    // MARK: - Flash Mode Picker

    private var flashModePicker: some View {
        SettingsSegmentedPicker(
            title: String(localized: "Flash Mode"),
            subtitle: String(localized: "Controls automatic flash behavior for photos"),
            options: CameraFlashMode.allCases.map { ($0.displayName, $0) },
            selection: $viewModel.flashMode,
            accentColor: AppAccent.primary
        )
        .accessibilityLabel(String(localized: "Select flash mode"))
    }

    // MARK: - HDR Mode Picker (Premium)

    private var hdrModePicker: some View {
        SettingsSegmentedPicker(
            title: String(localized: "HDR Mode"),
            subtitle: String(localized: "High Dynamic Range for better lighting in photos"),
            options: CameraHDRMode.allCases.map { ($0.displayName, $0) },
            selection: $viewModel.hdrMode,
            accentColor: AppAccent.primary,
            titleAccessory: {
                Image(systemName: "crown.fill")
                    .foregroundStyle(AppStatus.warning)
            }
        )
        .disabled(!isPremiumUnlocked)
        .accessibilityLabel(String(localized: "Select HDR mode"))
        .onTapGesture {
            if !isPremiumUnlocked {
                showPaywallAfterDismiss()
            }
        }
    }

    // MARK: - Photo Quality Picker (High/Maximum are Premium)

    private var photoQualityPicker: some View {
        VStack(alignment: .leading, spacing: Design.Spacing.xxSmall) {
            HStack(spacing: Design.Spacing.xSmall) {
                Text(String(localized: "Photo Quality"))
                    .font(.system(size: Design.FontSize.medium, weight: .medium))
                    .foregroundStyle(.white)
                
                Image(systemName: "crown.fill")
                    .font(.system(size: Design.FontSize.small))
                    .foregroundStyle(AppStatus.warning)
            }

            Text(isPremiumUnlocked 
                ? String(localized: "File size and image quality for saved photos")
                : String(localized: "Upgrade to unlock High quality"))
                .font(.system(size: Design.FontSize.caption))
                .foregroundStyle(.white.opacity(Design.Opacity.medium))

            // Custom picker with premium indicators
            HStack(spacing: Design.Spacing.small) {
                ForEach(PhotoQuality.allCases, id: \.self) { quality in
                    let isPremiumOption = quality == .high
                    let isDisabled = isPremiumOption && !isPremiumUnlocked
                    
                    Button {
                        if isDisabled {
                            showPaywallAfterDismiss()
                        } else {
                            viewModel.photoQuality = quality
                        }
                    } label: {
                        HStack(spacing: Design.Spacing.xxSmall) {
                            Text(quality.rawValue.capitalized)
                            if isPremiumOption && !isPremiumUnlocked {
                                Image(systemName: "lock.fill")
                                    .font(.system(size: Design.FontSize.xSmall))
                            }
                        }
                        .font(.system(size: Design.FontSize.body, weight: .medium))
                        .foregroundStyle(viewModel.photoQuality == quality ? .black : (isDisabled ? .white.opacity(Design.Opacity.light) : .white.opacity(Design.Opacity.strong)))
                        .padding(.vertical, Design.Spacing.small)
                        .frame(maxWidth: .infinity)
                        .background(
                            Capsule()
                                .fill(viewModel.photoQuality == quality ? AppAccent.primary : Color.white.opacity(Design.Opacity.subtle))
                        )
                    }
                    .buttonStyle(.plain)
                }
            }
            .padding(.vertical, Design.Spacing.xSmall)
            .accessibilityLabel(String(localized: "Select photo quality"))
        }
    }

    // MARK: - Camera Position Picker

    private var cameraPositionPicker: some View {
        SettingsSegmentedPicker(
            title: String(localized: "Camera"),
            subtitle: String(localized: "Choose between front and back camera lenses"),
            options: [
                (String(localized: "Front"), CameraPosition.front),
                (String(localized: "Back"), CameraPosition.back)
            ],
            selection: $viewModel.cameraPosition,
            accentColor: AppAccent.primary
        )
        .accessibilityLabel(String(localized: "Select camera position"))
    }

    // MARK: - Ring Light Brightness Slider

    private var ringLightBrightnessSlider: some View {
        SettingsSlider(
            title: String(localized: "Ring Light Brightness"),
            subtitle: String(localized: "Adjusts the brightness of the ring light"),
            value: $viewModel.ringLightOpacity,
            in: 0.1...1.0,
            step: 0.05,
            format: SliderFormat.percentage,
            accentColor: AppAccent.primary,
            leadingIcon: Image(systemName: "sun.min"),
            trailingIcon: Image(systemName: "sun.max.fill")
        )
        .accessibilityLabel(String(localized: "Ring light brightness"))
        .accessibilityValue("\(Int(viewModel.ringLightOpacity * 100)) percent")
    }

    // MARK: - Timer Picker (5s/10s are Premium)

    private var timerPicker: some View {
        VStack(alignment: .leading, spacing: Design.Spacing.xxSmall) {
            HStack(spacing: Design.Spacing.xSmall) {
                Text(String(localized: "Self-Timer"))
                    .font(.system(size: Design.FontSize.medium, weight: .medium))
                    .foregroundStyle(.white)
                
                Image(systemName: "crown.fill")
                    .font(.system(size: Design.FontSize.small))
                    .foregroundStyle(AppStatus.warning)
            }

            Text(isPremiumUnlocked
                ? String(localized: "Delay before photo capture for self-portraits")
                : String(localized: "Upgrade to unlock 5s and 10s timers"))
                .font(.system(size: Design.FontSize.caption))
                .foregroundStyle(.white.opacity(Design.Opacity.medium))

            // Custom picker with premium indicators
            HStack(spacing: Design.Spacing.small) {
                ForEach(TimerOption.allCases) { option in
                    let isPremiumOption = option == .five || option == .ten
                    let isDisabled = isPremiumOption && !isPremiumUnlocked
                    
                    Button {
                        if isDisabled {
                            showPaywallAfterDismiss()
                        } else {
                            viewModel.selectedTimer = option
                        }
                    } label: {
                        HStack(spacing: Design.Spacing.xxSmall) {
                            Text(option.displayName)
                            if isPremiumOption && !isPremiumUnlocked {
                                Image(systemName: "lock.fill")
                                    .font(.system(size: Design.FontSize.xSmall))
                            }
                        }
                        .font(.system(size: Design.FontSize.body, weight: .medium))
                        .foregroundStyle(viewModel.selectedTimer == option ? .black : (isDisabled ? .white.opacity(Design.Opacity.light) : .white.opacity(Design.Opacity.strong)))
                        .padding(.vertical, Design.Spacing.small)
                        .frame(maxWidth: .infinity)
                        .background(
                            Capsule()
                                .fill(viewModel.selectedTimer == option ? AppAccent.primary : Color.white.opacity(Design.Opacity.subtle))
                        )
                    }
                    .buttonStyle(.plain)
                }
            }
            .padding(.vertical, Design.Spacing.xSmall)
            .accessibilityLabel(String(localized: "Select self-timer duration"))
        }
    }
    
    // MARK: - Pro Section
    
    @ViewBuilder
    private var proSection: some View {
        if isPremiumUnlocked {
            // User has Pro - show status and manage link via Customer Center
            HStack(spacing: Design.Spacing.medium) {
                Image(systemName: "checkmark.seal.fill")
                    .font(.title2)
                    .foregroundStyle(AppStatus.success)
                
                VStack(alignment: .leading, spacing: Design.Spacing.xxSmall) {
                    Text(String(localized: "Pro Active"))
                        .font(.system(size: Design.FontSize.medium, weight: .semibold))
                        .foregroundStyle(.white)
                    
                    Button {
                        showCustomerCenter = true
                    } label: {
                        Text(String(localized: "Manage Subscription"))
                            .font(.system(size: Design.FontSize.caption))
                            .foregroundStyle(AppAccent.primary)
                    }
                }
                
                Spacer()
            }
            .padding(Design.Spacing.medium)
            .background(
                RoundedRectangle(cornerRadius: Design.CornerRadius.medium)
                    .fill(AppStatus.success.opacity(Design.Opacity.subtle))
                    .strokeBorder(AppStatus.success.opacity(Design.Opacity.light), lineWidth: Design.LineWidth.thin)
            )
            .accessibilityLabel(String(localized: "Pro subscription active"))
            .accessibilityHint(String(localized: "Tap Manage Subscription to view or cancel"))
            .presentCustomerCenter(isPresented: $showCustomerCenter)
        } else {
            // User doesn't have Pro - show upgrade button
            Button {
                dismiss()
                // Small delay to allow sheet to dismiss before showing paywall
                DispatchQueue.main.asyncAfter(deadline: .now() + 0.3) {
                    showPaywall = true
                }
            } label: {
                HStack(spacing: Design.Spacing.medium) {
                    Image(systemName: "crown.fill")
                        .font(.title2)
                        .foregroundStyle(AppStatus.warning)
                    
                    VStack(alignment: .leading, spacing: Design.Spacing.xxSmall) {
                        Text(String(localized: "Upgrade to Pro"))
                            .font(.system(size: Design.FontSize.medium, weight: .semibold))
                            .foregroundStyle(.white)
                        
                        Text(String(localized: "Premium colors, HDR, timers & more"))
                            .font(.system(size: Design.FontSize.caption))
                            .foregroundStyle(.white.opacity(Design.Opacity.medium))
                    }
                    
                    Spacer()
                    
                    Image(systemName: "chevron.right")
                        .font(.body)
                        .foregroundStyle(.white.opacity(Design.Opacity.medium))
                }
                .padding(Design.Spacing.medium)
                .background(
                    RoundedRectangle(cornerRadius: Design.CornerRadius.medium)
                        .fill(AppAccent.primary.opacity(Design.Opacity.subtle))
                        .strokeBorder(AppAccent.primary.opacity(Design.Opacity.light), lineWidth: Design.LineWidth.thin)
                )
            }
            .buttonStyle(.plain)
            .accessibilityLabel(String(localized: "Upgrade to Pro"))
            .accessibilityHint(String(localized: "Opens upgrade options"))
        }
    }
    
    // MARK: - iCloud Sync Section
    
    private var iCloudSyncSection: some View {
        iCloudSyncSettingsView(
            viewModel: viewModel,
            accentColor: AppAccent.primary,
            successColor: AppStatus.success,
            warningColor: AppStatus.warning
        )
    }
    
    // MARK: - Acknowledgments Section
    
    private var acknowledgmentsSection: some View {
        SettingsNavigationRow(
            title: String(localized: "Open Source Licenses"),
            subtitle: String(localized: "Third-party libraries used in this app"),
            backgroundColor: .clear
        ) {
            AppLicensesView()
        }
    }
    
    // MARK: - Premium Toggle Helper
    
    /// Creates a toggle with premium indicator (crown icon)
    /// - Parameters:
    ///   - title: The toggle title
    ///   - subtitle: The toggle subtitle/description
    ///   - isOn: Binding to the toggle state
    ///   - accessibilityHint: Accessibility hint for the toggle
    /// - Returns: A view containing the premium toggle
    @ViewBuilder
    private func premiumToggle(
        title: String,
        subtitle: String,
        isOn: Binding<Bool>,
        accessibilityHint: String
    ) -> some View {
        SettingsToggle(
            title: title,
            subtitle: subtitle,
            isOn: isOn,
            accentColor: AppAccent.primary,
            titleAccessory: {
                Image(systemName: "crown.fill")
                    .foregroundStyle(AppStatus.warning)
            }
        )
        .disabled(!isPremiumUnlocked)
        .accessibilityHint(accessibilityHint)
        .onTapGesture {
            if !isPremiumUnlocked {
                showPaywallAfterDismiss()
            }
        }
    }
    
    // MARK: - Branding Debug Section

    #if DEBUG
    private var brandingDebugSection: some View {
        VStack(spacing: Design.Spacing.small) {
            // Debug Premium Toggle
            SettingsToggle(
                title: "Enable Debug Premium",
                subtitle: "Unlock all premium features for testing",
                isOn: $viewModel.isDebugPremiumEnabled,
                accentColor: AppAccent.primary
            )
            
            // Reset Onboarding Button
            ResetOnboardingButton()
            
            // Icon Generator
            SettingsNavigationRow(
                title: "Icon Generator",
                subtitle: "Generate and save app icon to Files",
                backgroundColor: AppSurface.primary
            ) {
                IconGeneratorView(config: .selfieCam, appName: "SelfieCam")
            }
            
            // Branding Preview
            SettingsNavigationRow(
                title: "Branding Preview",
                subtitle: "Preview app icon and launch screen",
                backgroundColor: AppSurface.primary
            ) {
                BrandingPreviewView(
                    iconConfig: .selfieCam,
                    launchConfig: .selfieCam,
                    appName: "SelfieCam"
                )
            }
        }
    }
    #endif
}

// MARK: - Reset Onboarding Button

#if DEBUG
/// Debug button to reset onboarding state and show it again on next launch
struct ResetOnboardingButton: View {
    @AppStorage("hasCompletedOnboarding") private var hasCompletedOnboarding = true
    @State private var showConfirmation = false
    
    var body: some View {
        Button {
            hasCompletedOnboarding = false
            showConfirmation = true
        } label: {
            HStack {
                VStack(alignment: .leading, spacing: Design.Spacing.xxSmall) {
                    Text("Reset Onboarding")
                        .font(.system(size: Design.FontSize.medium, weight: .medium))
                        .foregroundStyle(.white)
                    
                    Text("Show onboarding flow on next app launch")
                        .font(.system(size: Design.FontSize.caption))
                        .foregroundStyle(.white.opacity(Design.Opacity.medium))
                }
                
                Spacer()
                
                Image(systemName: "arrow.counterclockwise")
                    .foregroundStyle(AppAccent.primary)
            }
        }
        .buttonStyle(.plain)
        .alert("Onboarding Reset", isPresented: $showConfirmation) {
            Button("OK", role: .cancel) {}
        } message: {
            Text("Onboarding will show again when you restart the app.")
        }
    }
}
#endif




#Preview {
    SettingsView(viewModel: SettingsViewModel(), showPaywall: .constant(false))
        .preferredColorScheme(.dark)
}
