import SwiftUI
import KeyboardShortcuts

struct MetricsSetupView: View {
    @EnvironmentObject private var transcriptionModelManager: TranscriptionModelManager
    @EnvironmentObject private var hotkeyManager: HotkeyManager
    @State private var isAccessibilityEnabled = AXIsProcessTrusted()
    @State private var isScreenRecordingEnabled = CGPreflightScreenCaptureAccess()
    
    var body: some View {
        ScrollView {
            VStack(spacing: ProatSpacing.l) {
                // Header
                VStack(spacing: ProatSpacing.s) {
                    AppIconView()
                        .frame(width: 80, height: 80)
                        .padding(.bottom, ProatSpacing.l)

                    VStack(spacing: ProatSpacing.xs) {
                        Text("Welkom bij Proat")
                            .font(ProatFont.display)
                            .foregroundColor(.proatText1)
                            .multilineTextAlignment(.center)

                        Text("Voltooi de installatie om te beginnen")
                            .font(ProatFont.body)
                            .foregroundColor(.proatText2)
                            .multilineTextAlignment(.center)
                    }
                }
                .padding(.top, ProatSpacing.l)
                .padding(.bottom, ProatSpacing.l)

                // Setup Steps
                VStack(alignment: .leading, spacing: 0) {
                    ForEach(0..<4) { index in
                        setupStep(for: index)
                        if index < 3 {
                            Divider().padding(.leading, 70)
                        }
                    }
                }
                .background(Color.proatBgRaised)
                .clipShape(RoundedRectangle(cornerRadius: ProatRadius.kaart, style: .continuous))
                .overlay(
                    RoundedRectangle(cornerRadius: ProatRadius.kaart, style: .continuous)
                        .stroke(Color.proatBorder, lineWidth: 1)
                )
                .proatShadowKaart()
                .padding(.horizontal)

                Spacer(minLength: ProatSpacing.l)

                // Action Button
                actionButton
                    .frame(maxWidth: 400)

                // Help Text
                helpText
            }
            .padding()
        }
        .frame(minWidth: 500, minHeight: 600)
        .background(Color.proatBgBase)
    }
    
    private func setupStep(for index: Int) -> some View {
        let stepInfo: (isCompleted: Bool, icon: String, title: String, description: String)
        
        switch index {
        case 0:
            stepInfo = (
                isCompleted: hotkeyManager.selectedHotkey1 != .none,
                icon: "command",
                title: "Sneltoets instellen",
                description: "Gebruik Proat overal met een sneltoets."
            )
        case 1:
            stepInfo = (
                isCompleted: isAccessibilityEnabled,
                icon: "hand.raised.fill",
                title: "Toegankelijkheid inschakelen",
                description: "Plak getranscribeerde tekst bij je cursor."
            )
        case 2:
            stepInfo = (
                isCompleted: isScreenRecordingEnabled,
                icon: "video.fill",
                title: "Schermopname inschakelen",
                description: "Krijg betere transcripties met schermcontext."
            )
        default:
            stepInfo = (
                isCompleted: transcriptionModelManager.currentTranscriptionModel != nil,
                icon: "arrow.down.to.line",
                title: "Model downloaden",
                description: "Kies een AI-model om te beginnen met transcriberen."
            )
        }
        
        return HStack(spacing: ProatSpacing.m) {
            Image(systemName: stepInfo.icon)
                .font(.system(size: 18))
                .frame(width: 40, height: 40)
                .background((stepInfo.isCompleted ? Color.proatOK : Color.proatTeal).opacity(0.14))
                .foregroundColor(stepInfo.isCompleted ? .proatOK : .proatTeal)
                .clipShape(Circle())

            VStack(alignment: .leading, spacing: 3) {
                Text(stepInfo.title)
                    .font(ProatFont.sectie)
                    .foregroundColor(.proatText1)
                Text(stepInfo.description)
                    .font(ProatFont.klein)
                    .foregroundColor(.proatText2)
            }

            Spacer()

            if stepInfo.isCompleted {
                Image(systemName: "checkmark.circle.fill")
                    .font(.system(size: 24))
                    .foregroundColor(.proatOK)
            } else {
                Image(systemName: "chevron.right")
                    .font(.system(size: 14, weight: .bold))
                    .foregroundColor(.proatText3)
            }
        }
        .padding()
    }
    
    private var actionButton: some View {
        Button(action: handleActionButton) {
            HStack {
                Text(getActionButtonTitle())
                    .fontWeight(.semibold)
                Image(systemName: "arrow.right")
            }
            .font(ProatFont.body)
            .frame(maxWidth: .infinity)
            .padding(.vertical, ProatSpacing.s)
            .background(LinearGradient.proatTeal)
            .foregroundColor(.white)
            .clipShape(RoundedRectangle(cornerRadius: ProatRadius.knop, style: .continuous))
        }
        .buttonStyle(.plain)
        .proatShadowKaart()
    }
    
    private func handleActionButton() {
        if isShortcutAndAccessibilityGranted {
            openModelManagement()
        } else {
            // Handle different permission requests based on which one is missing
            if hotkeyManager.selectedHotkey1 == .none {
                openSettings()
            } else if !AXIsProcessTrusted() {
                if let url = URL(string: "x-apple.systempreferences:com.apple.preference.security?Privacy_Accessibility") {
                    NSWorkspace.shared.open(url)
                }
            } else if !CGPreflightScreenCaptureAccess() {
                CGRequestScreenCaptureAccess()
                // After requesting, open system preferences as fallback
                if let url = URL(string: "x-apple.systempreferences:com.apple.preference.security?Privacy_ScreenCapture") {
                    NSWorkspace.shared.open(url)
                }
            }
        }
    }
    
    private func getActionButtonTitle() -> String {
        if hotkeyManager.selectedHotkey1 == .none {
            return "Sneltoets configureren"
        } else if !AXIsProcessTrusted() {
            return "Toegankelijkheid inschakelen"
        } else if !CGPreflightScreenCaptureAccess() {
            return "Schermopname inschakelen"
        } else if transcriptionModelManager.currentTranscriptionModel == nil {
            return "Model downloaden"
        }
        return "Aan de slag"
    }
    
    private var helpText: some View {
        Text("Hulp nodig? Bekijk het Help-menu voor ondersteuningsopties")
            .font(ProatFont.klein)
            .foregroundColor(.proatText3)
    }
    
    private var isShortcutAndAccessibilityGranted: Bool {
        hotkeyManager.selectedHotkey1 != .none &&
        AXIsProcessTrusted() && 
        CGPreflightScreenCaptureAccess()
    }
    
    private func openSettings() {
        NotificationCenter.default.post(
            name: .navigateToDestination,
            object: nil,
            userInfo: ["destination": "Settings"]
        )
    }
    
    private func openModelManagement() {
        NotificationCenter.default.post(
            name: .navigateToDestination,
            object: nil,
            userInfo: ["destination": "AI Models"]
        )
    }
}

