//
//  OnboardingPermissionView.swift
//  SelfieCam
//
//  Reusable permission request screen for camera and photo library access.
//  Handles permission states and provides appropriate UI for each state.
//  Supports landscape and iPad layouts with max width constraints.
//

import SwiftUI
import Bedrock

// MARK: - Permission Type

/// Types of permissions the onboarding can request
enum OnboardingPermissionType {
    case camera
    case microphone
    case photoLibrary
    
    var icon: String {
        switch self {
        case .camera: return "camera.fill"
        case .microphone: return "mic.fill"
        case .photoLibrary: return "photo.on.rectangle.angled"
        }
    }
    
    var title: String {
        switch self {
        case .camera: return String(localized: "Camera Access")
        case .microphone: return String(localized: "Microphone Access")
        case .photoLibrary: return String(localized: "Photo Library")
        }
    }
    
    var description: String {
        switch self {
        case .camera:
            return String(localized: "SelfieCam needs camera access to show your live preview, apply real-time filters, and capture high-quality photos.")
        case .microphone:
            return String(localized: "The camera requires microphone access to initialize properly. Audio is not recorded or stored.")
        case .photoLibrary:
            return String(localized: "Save your photos directly to your library for easy access and sharing.")
        }
    }
    
    var buttonTitle: String {
        switch self {
        case .camera: return String(localized: "Enable Camera")
        case .microphone: return String(localized: "Enable Microphone")
        case .photoLibrary: return String(localized: "Enable Photos")
        }
    }
    
    var deniedTitle: String {
        switch self {
        case .camera: return String(localized: "Camera Access Required")
        case .microphone: return String(localized: "Microphone Access Required")
        case .photoLibrary: return String(localized: "Photo Access Denied")
        }
    }
    
    var deniedDescription: String {
        switch self {
        case .camera:
            return String(localized: "SelfieCam requires camera access to function. Please enable it in Settings to continue.")
        case .microphone:
            return String(localized: "The camera framework requires microphone access to work. Please enable it in Settings to continue.")
        case .photoLibrary:
            return String(localized: "Without photo library access, you can still share photos directly but won't be able to save them automatically.")
        }
    }
    
    /// Whether this permission is required to proceed
    var isRequired: Bool {
        switch self {
        case .camera: return true
        case .microphone: return true
        case .photoLibrary: return false
        }
    }
}

// MARK: - Permission View

struct OnboardingPermissionView: View {
    @Bindable var viewModel: OnboardingViewModel
    let permissionType: OnboardingPermissionType
    
    /// Current permission status for this permission type
    private var permissionStatus: PermissionStatus {
        switch permissionType {
        case .camera: return viewModel.cameraPermissionStatus
        case .microphone: return viewModel.microphonePermissionStatus
        case .photoLibrary: return viewModel.photoPermissionStatus
        }
    }
    
    /// Whether this permission has been granted
    private var isGranted: Bool {
        permissionStatus == .authorized
    }
    
    /// Whether this permission was explicitly denied
    private var isDenied: Bool {
        permissionStatus == .denied
    }
    
    /// Icon color based on permission state
    private var iconColor: Color {
        isGranted ? AppStatus.success : AppAccent.primary
    }
    
    var body: some View {
        OnboardingContentContainer {
            VStack(spacing: Design.Spacing.xLarge) {
                Spacer()
                
                // Permission icon with status indicator
                ZStack {
                    OnboardingHeroIcon(
                        systemName: permissionType.icon,
                        color: iconColor
                    )
                }
                .overlay(alignment: .bottomTrailing) {
                    // Checkmark overlay when granted
                    if isGranted {
                        Circle()
                            .fill(AppStatus.success)
                            .frame(width: Design.Spacing.xLarge, height: Design.Spacing.xLarge)
                            .overlay {
                                SymbolIcon("checkmark", size: .inline, color: .white, weight: .bold)
                            }
                            .offset(x: Design.Spacing.medium, y: Design.Spacing.medium)
                    }
                }
                
                // Title and description
                OnboardingSectionTitle(
                    title: isDenied ? permissionType.deniedTitle : permissionType.title,
                    subtitle: isDenied ? permissionType.deniedDescription : permissionType.description
                )
                .padding(.horizontal, Design.Spacing.large)
                
                Spacer()
                
                // Action buttons
                VStack(spacing: Design.Spacing.medium) {
                    if isGranted {
                        // Already granted - show continue button
                        OnboardingPrimaryButton(
                            title: String(localized: "Continue"),
                            action: { viewModel.advanceToNextStep() }
                        )
                    } else if isDenied {
                        // Denied - show open settings button
                        OnboardingPrimaryButton(
                            title: String(localized: "Open Settings"),
                            action: { viewModel.openSettings() }
                        )
                        
                        // For non-required permissions, allow skipping
                        if !permissionType.isRequired {
                            OnboardingSecondaryButton(
                                title: String(localized: "Skip for Now"),
                                action: { viewModel.advanceToNextStep() }
                            )
                        }
                    } else {
                        // Not determined - show request button
                        OnboardingPrimaryButton(
                            title: permissionType.buttonTitle,
                            action: {
                                Task {
                                    switch permissionType {
                                    case .camera:
                                        await viewModel.requestCameraPermission()
                                    case .microphone:
                                        await viewModel.requestMicrophonePermission()
                                    case .photoLibrary:
                                        await viewModel.requestPhotoPermission()
                                    }
                                    
                                    // Auto-advance if granted (or skip for optional permissions)
                                    if viewModel.canProceed {
                                        viewModel.advanceToNextStep()
                                    }
                                }
                            }
                        )
                    }
                }
                .padding(.horizontal, Design.Spacing.xLarge)
                .padding(.bottom, Design.Spacing.xLarge)
            }
            .padding(.horizontal, Design.Spacing.medium)
        }
        .onAppear {
            // Refresh permission status when view appears (in case user changed in Settings)
            viewModel.updatePermissionStates()
        }
    }
}

// MARK: - Preview

#Preview("Camera Permission") {
    OnboardingPermissionView(
        viewModel: OnboardingViewModel(),
        permissionType: .camera
    )
    .background(AppSurface.primary)
    .preferredColorScheme(.dark)
}

#Preview("Photo Library Permission") {
    OnboardingPermissionView(
        viewModel: OnboardingViewModel(),
        permissionType: .photoLibrary
    )
    .background(AppSurface.primary)
    .preferredColorScheme(.dark)
}

#Preview("Landscape", traits: .landscapeLeft) {
    OnboardingPermissionView(
        viewModel: OnboardingViewModel(),
        permissionType: .camera
    )
    .background(AppSurface.primary)
    .preferredColorScheme(.dark)
}
