import SwiftUI
import Bedrock
import AVFoundation

struct QRScannerView: View {
    @Environment(\.dismiss) private var dismiss
    let onScan: (String) -> Void
    
    @State private var scannedCode: String?
    @State private var isScanning = true
    @State private var showingPermissionDenied = false
    
    var body: some View {
        NavigationStack {
            ZStack {
                if isScanning {
                    QRScannerRepresentable(scannedCode: $scannedCode)
                        .ignoresSafeArea()
                    
                    // Overlay with scanning frame
                    ScannerOverlayView()
                }
                
                if let scannedCode {
                    ScannedResultView(code: scannedCode) {
                        onScan(scannedCode)
                    }
                }
            }
            .navigationTitle(String.localized("Scan Card"))
            .navigationBarTitleDisplayMode(.inline)
            .toolbar {
                ToolbarItem(placement: .cancellationAction) {
                    Button(String.localized("Cancel")) {
                        dismiss()
                    }
                }
            }
            .onChange(of: scannedCode) { _, newValue in
                if newValue != nil {
                    isScanning = false
                }
            }
            .onAppear {
                checkCameraPermission()
            }
            .alert(String.localized("Camera Access Required"), isPresented: $showingPermissionDenied) {
                Button(String.localized("Open Settings")) {
                    if let url = URL(string: UIApplication.openSettingsURLString) {
                        UIApplication.shared.open(url)
                    }
                }
                Button(String.localized("Cancel"), role: .cancel) {
                    dismiss()
                }
            } message: {
                Text("Please allow camera access in Settings to scan QR codes.")
            }
        }
    }
    
    private func checkCameraPermission() {
        switch AVCaptureDevice.authorizationStatus(for: .video) {
        case .authorized:
            break
        case .notDetermined:
            AVCaptureDevice.requestAccess(for: .video) { granted in
                if !granted {
                    Task { @MainActor in
                        showingPermissionDenied = true
                    }
                }
            }
        case .denied, .restricted:
            showingPermissionDenied = true
        @unknown default:
            break
        }
    }
}

#Preview {
    QRScannerView { code in
        Design.debugLog("Scanned: \(code)")
    }
}
