import SwiftUI

/// Compact panel-optimized performance analysis view for sliding panels and sidebars.
struct PerformanceAnalysisPanelView: View {
    let transcriptions: [Transcription]
    let onClose: () -> Void
    private let analysis: PerformanceAnalyzer.AnalysisResult

    init(transcriptions: [Transcription], onClose: @escaping () -> Void) {
        self.transcriptions = transcriptions
        self.onClose = onClose
        self.analysis = PerformanceAnalyzer.analyze(transcriptions: transcriptions)
    }

    var body: some View {
        VStack(spacing: 0) {
            header
                .padding(.horizontal, ProatSpacing.l)
                .padding(.vertical, ProatSpacing.s)
                .background(Color.proatBgRaised)
                .overlay(Rectangle().fill(Color.proatBorder).frame(height: 1), alignment: .bottom)
                .zIndex(1)

            ScrollView {
                VStack(alignment: .leading, spacing: 20) {
                    summarySection
                    systemInfoSection

                    if !analysis.transcriptionModels.isEmpty {
                        transcriptionModelsSection
                    }

                    if !analysis.enhancementModels.isEmpty {
                        enhancementModelsSection
                    }
                }
                .padding(16)
            }
        }
    }

    // MARK: - Header

    private var header: some View {
        HStack(spacing: ProatSpacing.s) {
            Text("Prestatieanalyse")
                .font(ProatFont.sectie)
                .foregroundColor(.proatText1)
            Spacer()
            Button(action: onClose) {
                Image(systemName: "xmark")
                    .font(.system(size: 14, weight: .medium))
                    .foregroundColor(.proatText2)
                    .padding(6)
                    .background(Color.proatBgSunken)
                    .clipShape(Circle())
            }
            .buttonStyle(.plain)
        }
    }

    // MARK: - Summary

    private var summarySection: some View {
        VStack(alignment: .leading, spacing: 8) {
            sectionHeader("Samenvatting")

            HStack(spacing: ProatSpacing.xs) {
                summaryPill(icon: "doc.text.fill", value: "\(analysis.totalTranscripts)", label: "Totaal", color: .proatTeal)
                summaryPill(icon: "waveform.path.ecg", value: "\(analysis.totalWithTranscriptionData)", label: "Analyseerbaar", color: .proatTeal)
                summaryPill(icon: "sparkles", value: "\(analysis.totalEnhancedFiles)", label: "Verfijnd", color: .proatTeal)
            }
        }
    }

    private func summaryPill(icon: String, value: String, label: String, color: Color) -> some View {
        VStack(spacing: 4) {
            Image(systemName: icon)
                .font(.system(size: 14, weight: .medium))
                .foregroundColor(.proatTeal)
            Text(value)
                .font(.system(size: 18, weight: .bold, design: .rounded))
                .foregroundColor(.proatText1)
            Text(label)
                .font(ProatFont.klein)
                .foregroundColor(.proatText3)
        }
        .frame(maxWidth: .infinity)
        .padding(.vertical, ProatSpacing.xs)
        .proatCard(padding: ProatSpacing.xs)
    }

    // MARK: - System Info

    private var systemInfoSection: some View {
        VStack(alignment: .leading, spacing: 8) {
            sectionHeader("Systeeminformatie")

            VStack(spacing: 0) {
                infoRow(label: "Apparaat", value: PerformanceAnalyzer.getMacModel())
                Rectangle().fill(Color.proatBorder).frame(height: 1).padding(.horizontal, 10)
                infoRow(label: "Processor", value: PerformanceAnalyzer.getCPUInfo())
                Rectangle().fill(Color.proatBorder).frame(height: 1).padding(.horizontal, 10)
                infoRow(label: "Geheugen", value: PerformanceAnalyzer.getMemoryInfo())
            }
            .background(Color.proatBgRaised)
            .clipShape(RoundedRectangle(cornerRadius: ProatRadius.kaart, style: .continuous))
            .overlay(
                RoundedRectangle(cornerRadius: ProatRadius.kaart, style: .continuous)
                    .stroke(Color.proatBorder, lineWidth: 1)
            )
        }
    }

    private func infoRow(label: String, value: String) -> some View {
        HStack {
            Text(label)
                .font(ProatFont.klein)
                .foregroundColor(.proatText2)
            Spacer(minLength: 4)
            Text(value)
                .font(ProatFont.klein)
                .fontWeight(.semibold)
                .foregroundColor(.proatText1)
                .lineLimit(1)
        }
        .padding(.horizontal, ProatSpacing.s)
        .padding(.vertical, ProatSpacing.xs)
    }

    // MARK: - Transcription Models

    private let gridColumns = [
        GridItem(.flexible(), spacing: 12),
        GridItem(.flexible(), spacing: 12)
    ]

    private var transcriptionModelsSection: some View {
        VStack(alignment: .leading, spacing: 10) {
            sectionHeader("Transcriptiemodellen")

            LazyVGrid(columns: gridColumns, spacing: 12) {
                ForEach(analysis.transcriptionModels) { modelStat in
                    transcriptionModelTile(modelStat)
                }
            }
        }
    }

    private func transcriptionModelTile(_ modelStat: PerformanceAnalyzer.ModelStat) -> some View {
        VStack(spacing: ProatSpacing.xs) {
            // Model name + count
            VStack(spacing: 2) {
                Text(modelStat.name)
                    .font(ProatFont.body)
                    .fontWeight(.semibold)
                    .foregroundColor(.proatText1)
                    .lineLimit(1)
                    .minimumScaleFactor(0.7)
                Text("\(modelStat.fileCount) transcripties")
                    .font(ProatFont.klein)
                    .foregroundColor(.proatText3)
            }
            .frame(maxWidth: .infinity)

            // Hero metric
            VStack(spacing: 3) {
                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)
            }

            Rectangle().fill(Color.proatBorder).frame(height: 1)
                .padding(.horizontal, 8)

            // Secondary metrics
            HStack(spacing: 0) {
                VStack(spacing: 2) {
                    Text(formatDuration(modelStat.avgAudioDuration))
                        .font(ProatFont.mono)
                        .foregroundColor(.proatText1)
                    Text("Gem. audio")
                        .font(ProatFont.klein)
                        .foregroundColor(.proatText3)
                }
                .frame(maxWidth: .infinity)

                Rectangle()
                    .fill(Color.proatBorder)
                    .frame(width: 1, height: 24)

                VStack(spacing: 2) {
                    Text(String(format: "%.2fs", modelStat.avgProcessingTime))
                        .font(ProatFont.mono)
                        .foregroundColor(.proatText1)
                    Text("Gem. verwerking")
                        .font(ProatFont.klein)
                        .foregroundColor(.proatText3)
                }
                .frame(maxWidth: .infinity)
            }
        }
        .proatCard(padding: ProatSpacing.s)
    }

    // MARK: - Enhancement Models

    private var enhancementModelsSection: some View {
        VStack(alignment: .leading, spacing: 10) {
            sectionHeader("Verfijningsmodellen")

            LazyVGrid(columns: gridColumns, spacing: 12) {
                ForEach(analysis.enhancementModels) { modelStat in
                    enhancementModelTile(modelStat)
                }
            }
        }
    }

    private func enhancementModelTile(_ modelStat: PerformanceAnalyzer.ModelStat) -> some View {
        VStack(spacing: ProatSpacing.xs) {
            // Model name + count
            VStack(spacing: 2) {
                Text(modelStat.name)
                    .font(ProatFont.body)
                    .fontWeight(.semibold)
                    .foregroundColor(.proatText1)
                    .lineLimit(1)
                    .minimumScaleFactor(0.7)
                Text("\(modelStat.fileCount) transcripties")
                    .font(ProatFont.klein)
                    .foregroundColor(.proatText3)
            }
            .frame(maxWidth: .infinity)

            // Hero metric
            VStack(spacing: 3) {
                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)
            }
        }
        .proatCard(padding: ProatSpacing.s)
    }

    // MARK: - Helpers

    private func sectionHeader(_ title: String) -> some View {
        Text(title)
            .font(ProatFont.klein)
            .fontWeight(.semibold)
            .foregroundColor(.proatText3)
            .textCase(.uppercase)
            .tracking(0.5)
    }

    private func formatDuration(_ duration: TimeInterval) -> String {
        let formatter = DateComponentsFormatter()
        formatter.allowedUnits = [.minute, .second]
        formatter.unitsStyle = .abbreviated
        return formatter.string(from: duration) ?? "0s"
    }
}
