import SwiftUI

// MARK: - Shared Analysis Logic

enum PanelMode {
    case info
    case analysis
}

struct PerformanceAnalyzer {
    struct AnalysisResult {
        let totalTranscripts: Int
        let totalWithTranscriptionData: Int
        let totalAudioDuration: TimeInterval
        let totalEnhancedFiles: Int
        let transcriptionModels: [ModelStat]
        let enhancementModels: [ModelStat]
    }

    struct ModelStat: Identifiable {
        let id = UUID()
        let name: String
        let fileCount: Int
        let totalProcessingTime: TimeInterval
        let avgProcessingTime: TimeInterval
        let avgAudioDuration: TimeInterval
        let speedFactor: Double
    }

    static func analyze(transcriptions: [Transcription]) -> AnalysisResult {
        let totalTranscripts = transcriptions.count
        let totalWithTranscriptionData = transcriptions.filter { $0.transcriptionDuration != nil }.count
        let totalAudioDuration = transcriptions.reduce(0) { $0 + $1.duration }
        let totalEnhancedFiles = transcriptions.filter { $0.enhancedText != nil && $0.enhancementDuration != nil }.count

        let transcriptionStats = processStats(
            for: transcriptions,
            modelNameKeyPath: \.transcriptionModelName,
            durationKeyPath: \.transcriptionDuration,
            audioDurationKeyPath: \.duration
        )

        let enhancementStats = processStats(
            for: transcriptions,
            modelNameKeyPath: \.aiEnhancementModelName,
            durationKeyPath: \.enhancementDuration
        )

        return AnalysisResult(
            totalTranscripts: totalTranscripts,
            totalWithTranscriptionData: totalWithTranscriptionData,
            totalAudioDuration: totalAudioDuration,
            totalEnhancedFiles: totalEnhancedFiles,
            transcriptionModels: transcriptionStats,
            enhancementModels: enhancementStats
        )
    }

    static func processStats(for transcriptions: [Transcription],
                             modelNameKeyPath: KeyPath<Transcription, String?>,
                             durationKeyPath: KeyPath<Transcription, TimeInterval?>,
                             audioDurationKeyPath: KeyPath<Transcription, TimeInterval>? = nil) -> [ModelStat] {

        let relevantTranscriptions = transcriptions.filter {
            $0[keyPath: modelNameKeyPath] != nil && $0[keyPath: durationKeyPath] != nil
        }

        let groupedByModel = Dictionary(grouping: relevantTranscriptions) {
            $0[keyPath: modelNameKeyPath] ?? "Onbekend"
        }

        return groupedByModel.map { modelName, items in
            let fileCount = items.count
            let totalProcessingTime = items.reduce(0) { $0 + ($1[keyPath: durationKeyPath] ?? 0) }
            let avgProcessingTime = totalProcessingTime / Double(fileCount)

            let totalAudioDuration = items.reduce(0) { $0 + $1.duration }
            let avgAudioDuration = totalAudioDuration / Double(fileCount)

            var speedFactor = 0.0
            if let audioDurationKeyPath = audioDurationKeyPath, totalProcessingTime > 0 {
                speedFactor = totalAudioDuration / totalProcessingTime
            }

            return ModelStat(
                name: modelName,
                fileCount: fileCount,
                totalProcessingTime: totalProcessingTime,
                avgProcessingTime: avgProcessingTime,
                avgAudioDuration: avgAudioDuration,
                speedFactor: speedFactor
            )
        }.sorted { $0.avgProcessingTime < $1.avgProcessingTime }
    }

    static func getMacModel() -> String {
        var size = 0
        sysctlbyname("hw.model", nil, &size, nil, 0)
        var machine = [CChar](repeating: 0, count: size)
        sysctlbyname("hw.model", &machine, &size, nil, 0)
        return String(cString: machine)
    }

    static func getCPUInfo() -> String {
        var size = 0
        sysctlbyname("machdep.cpu.brand_string", nil, &size, nil, 0)
        var buffer = [CChar](repeating: 0, count: size)
        sysctlbyname("machdep.cpu.brand_string", &buffer, &size, nil, 0)
        return String(cString: buffer)
    }

    static func getMemoryInfo() -> String {
        let totalMemory = ProcessInfo.processInfo.physicalMemory
        return ByteCountFormatter.string(fromByteCount: Int64(totalMemory), countStyle: .memory)
    }
}

// MARK: - Sheet View (existing)

struct PerformanceAnalysisView: View {
    @Environment(\.dismiss) private var dismiss
    let transcriptions: [Transcription]
    private let analysis: PerformanceAnalyzer.AnalysisResult

    private let columns: [GridItem] = [
        GridItem(.adaptive(minimum: 250), spacing: 16)
    ]

    init(transcriptions: [Transcription]) {
        self.transcriptions = transcriptions
        self.analysis = PerformanceAnalyzer.analyze(transcriptions: transcriptions)
    }

    var body: some View {
        VStack(spacing: 0) {
            header
                .padding()

            Divider()

            ScrollView {
                VStack(alignment: .leading, spacing: 30) {
                    summarySection
                    
                    systemInfoSection
                    
                    if !analysis.transcriptionModels.isEmpty {
                        transcriptionPerformanceSection
                    }
                    
                    if !analysis.enhancementModels.isEmpty {
                        enhancementPerformanceSection
                    }
                }
                .padding()
            }
        }
        .frame(minWidth: 550, idealWidth: 600, maxWidth: 700, minHeight: 600, idealHeight: 750, maxHeight: 900)
        .background(Color.proatBgBase)
    }

    private var header: some View {
        HStack {
            Text("Prestatieanalyse")
                .font(ProatFont.titel)
                .foregroundColor(.proatText1)
            Spacer()
            Button {
                dismiss()
            } label: {
                Image(systemName: "xmark")
                    .foregroundColor(.proatText2)
            }
            .buttonStyle(.borderless)
        }
    }

    private var summarySection: some View {
        HStack(spacing: ProatSpacing.s) {
            SummaryCard(
                icon: "doc.text.fill",
                value: "\(analysis.totalTranscripts)",
                label: "Totaal transcripties",
                color: .proatTeal
            )
            SummaryCard(
                icon: "waveform.path.ecg",
                value: "\(analysis.totalWithTranscriptionData)",
                label: "Analyseerbaar",
                color: .proatTeal
            )
            SummaryCard(
                icon: "sparkles",
                value: "\(analysis.totalEnhancedFiles)",
                label: "Verfijnd",
                color: .proatTeal
            )
        }
    }

    private var systemInfoSection: some View {
        VStack(alignment: .leading, spacing: ProatSpacing.m) {
            Text("Systeeminformatie")
                .font(ProatFont.titel)
                .foregroundColor(.proatText1)

            HStack(spacing: ProatSpacing.s) {
                SystemInfoCard(label: "Apparaat", value: PerformanceAnalyzer.getMacModel())
                SystemInfoCard(label: "Processor", value: PerformanceAnalyzer.getCPUInfo())
                SystemInfoCard(label: "Geheugen", value: PerformanceAnalyzer.getMemoryInfo())
            }
        }
    }

    private var transcriptionPerformanceSection: some View {
        VStack(alignment: .leading, spacing: ProatSpacing.m) {
            Text("Transcriptiemodellen")
                .font(ProatFont.titel)
                .foregroundColor(.proatText1)

            LazyVGrid(columns: columns, spacing: ProatSpacing.m) {
                ForEach(analysis.transcriptionModels) { modelStat in
                    TranscriptionModelCard(modelStat: modelStat)
                }
            }
        }
    }

    private var enhancementPerformanceSection: some View {
        VStack(alignment: .leading, spacing: ProatSpacing.m) {
            Text("Verfijningsmodellen")
                .font(ProatFont.titel)
                .foregroundColor(.proatText1)

            LazyVGrid(columns: columns, spacing: ProatSpacing.m) {
                ForEach(analysis.enhancementModels) { modelStat in
                    EnhancementModelCard(modelStat: modelStat)
                }
            }
        }
    }
    
    private func formatDuration(_ duration: TimeInterval) -> String {
        let formatter = DateComponentsFormatter()
        formatter.allowedUnits = [.minute, .second]
        formatter.unitsStyle = .abbreviated
        return formatter.string(from: duration) ?? "0s"
    }
}

// MARK: - Subviews

struct SummaryCard: View {
    let icon: String
    let value: String
    let label: String
    let color: Color

    var body: some View {
        VStack(spacing: ProatSpacing.xs) {
            Image(systemName: icon)
                .font(.system(size: 20, weight: .medium))
                .foregroundColor(.proatTeal)

            Text(value)
                .font(.system(.title2, design: .rounded, weight: .bold))
                .foregroundColor(.proatText1)

            Text(label)
                .font(ProatFont.klein)
                .foregroundColor(.proatText3)
        }
        .frame(maxWidth: .infinity, minHeight: 100)
        .proatCard(padding: ProatSpacing.m)
    }
}

struct InfoRow: View {
    let label: String
    let value: String

    var body: some View {
        HStack {
            Text(label)
                .font(ProatFont.sectie)
                .foregroundColor(.proatText2)
            Spacer()
            Text(value)
                .font(ProatFont.body)
                .foregroundColor(.proatText1)
        }
    }
}

struct SystemInfoCard: View {
    let label: String
    let value: String

    var body: some View {
        VStack(alignment: .leading, spacing: 4) {
            Text(label)
                .font(ProatFont.klein)
                .fontWeight(.medium)
                .foregroundColor(.proatText3)
                .textCase(.uppercase)

            Text(value)
                .font(ProatFont.body)
                .fontWeight(.semibold)
                .foregroundColor(.proatText1)
                .lineLimit(2)
                .fixedSize(horizontal: false, vertical: true)
        }
        .frame(maxWidth: .infinity, minHeight: 60, alignment: .leading)
        .proatCard(padding: ProatSpacing.s)
    }
}

struct TranscriptionModelCard: View {
    let modelStat: PerformanceAnalyzer.ModelStat

    var body: some View {
        VStack(alignment: .leading, spacing: ProatSpacing.s) {
            // Model name and transcript count
            HStack(alignment: .firstTextBaseline) {
                Text(modelStat.name)
                    .font(ProatFont.sectie)
                    .foregroundColor(.proatText1)
                    .lineLimit(1)
                    .minimumScaleFactor(0.7)

                Spacer()

                Text("\(modelStat.fileCount) transcripties")
                    .font(ProatFont.klein)
                    .foregroundColor(.proatText3)
            }

            Rectangle().fill(Color.proatBorder).frame(height: 1)

            VStack(spacing: ProatSpacing.m) {
                // Main metric: Speed Factor
                VStack {
                    Text(String(format: "%.1fx", modelStat.speedFactor))
                        .font(.system(size: 24, weight: .bold, design: .rounded))
                        .foregroundColor(.proatTeal)
                    Text("Sneller dan realtime")
                        .font(ProatFont.klein)
                        .foregroundColor(.proatText3)
                }
                .frame(maxWidth: .infinity)

                Rectangle().fill(Color.proatBorder).frame(height: 1)

                // Secondary metrics
                HStack {
                    MetricDisplay(
                        title: "Gem. audio",
                        value: formatDuration(modelStat.avgAudioDuration),
                        color: .proatText1
                    )
                    Spacer()
                    MetricDisplay(
                        title: "Gem. verwerkingstijd",
                        value: String(format: "%.2f s", modelStat.avgProcessingTime),
                        color: .proatText1
                    )
                }
            }
        }
        .proatCard(padding: ProatSpacing.m)
    }
    
    private func formatDuration(_ duration: TimeInterval) -> String {
        let formatter = DateComponentsFormatter()
        formatter.allowedUnits = [.minute, .second]
        formatter.unitsStyle = .abbreviated
        return formatter.string(from: duration) ?? "0s"
    }
}

struct EnhancementModelCard: View {
    let modelStat: PerformanceAnalyzer.ModelStat

    var body: some View {
        VStack(alignment: .leading, spacing: ProatSpacing.s) {
            // Model name and transcript count
            HStack(alignment: .firstTextBaseline) {
                Text(modelStat.name)
                    .font(ProatFont.sectie)
                    .foregroundColor(.proatText1)
                    .lineLimit(1)
                    .minimumScaleFactor(0.7)

                Spacer()

                Text("\(modelStat.fileCount) transcripties")
                    .font(ProatFont.klein)
                    .foregroundColor(.proatText3)
            }

            Rectangle().fill(Color.proatBorder).frame(height: 1)

            VStack(alignment: .center) {
                Text(String(format: "%.2f s", modelStat.avgProcessingTime))
                    .font(.system(size: 24, weight: .bold, design: .rounded))
                    .foregroundColor(.proatText1)
                Text("Gem. verfijningstijd")
                    .font(ProatFont.klein)
                    .foregroundColor(.proatText3)
            }
            .frame(maxWidth: .infinity)
        }
        .proatCard(padding: ProatSpacing.m)
    }
}

struct MetricCardBackground: View {
    let color: Color
    
    var body: some View {
        RoundedRectangle(cornerRadius: ProatRadius.kaart, style: .continuous)
            .fill(Color.proatBgRaised)
            .overlay(
                RoundedRectangle(cornerRadius: ProatRadius.kaart, style: .continuous)
                    .stroke(Color.proatBorder, lineWidth: 1)
            )
            .proatShadowRust()
    }
}

struct MetricDisplay: View {
    let title: String
    let value: String
    let color: Color
    
    var body: some View {
        VStack(alignment: .leading, spacing: 4) {
            Text(title)
                .font(ProatFont.klein)
                .foregroundColor(.proatText3)
                .textCase(.uppercase)
                .tracking(0.5)

            Text(value)
                .font(ProatFont.mono)
                .fontWeight(.semibold)
                .foregroundColor(.proatText1)
        }
    }
}
