import SwiftUI
import AppKit
// MARK: - Local Model Card View
struct WhisperModelCardView: View {
    let model: WhisperModel
    let isDownloaded: Bool
    let isCurrent: Bool
    let downloadProgress: [String: Double]
    let modelURL: URL?
    let isWarming: Bool
    
    // Actions
    var deleteAction: () -> Void
    var setDefaultAction: () -> Void
    var downloadAction: () -> Void
    private var isDownloading: Bool {
        downloadProgress.keys.contains(model.name + "_main") || 
        downloadProgress.keys.contains(model.name + "_coreml")
    }
    
    var body: some View {
        HStack(alignment: .top, spacing: ProatSpacing.m) {
            // Main Content
            VStack(alignment: .leading, spacing: ProatSpacing.xs - 2) {
                headerSection
                metadataSection
                descriptionSection
                progressSection
            }
            .frame(maxWidth: .infinity, alignment: .leading)

            // Action Controls
            actionSection
        }
        .padding(ProatSpacing.m)
        .background(ProatModelCardBackground(isSelected: isCurrent))
    }

    private var headerSection: some View {
        HStack(alignment: .firstTextBaseline) {
            Text(model.displayName)
                .font(ProatFont.sectie)
                .foregroundColor(.proatText1)

            Spacer()
        }
    }

    private var metadataSection: some View {
        HStack(spacing: ProatSpacing.s) {
            // Language
            Label(model.language, systemImage: "globe")
                .font(ProatFont.klein)
                .foregroundColor(.proatText2)
                .lineLimit(1)

            // Size
            Label(model.size, systemImage: "internaldrive")
                .font(ProatFont.klein)
                .foregroundColor(.proatText2)
                .lineLimit(1)

            // Speed
            HStack(spacing: 3) {
                Text("Snelheid")
                    .font(.system(size: 12, weight: .medium))
                    .foregroundColor(.proatText2)
                progressDotsWithNumber(value: model.speed * 10)
            }
            .lineLimit(1)
            .fixedSize(horizontal: true, vertical: false)

            // Accuracy
            HStack(spacing: 3) {
                Text("Nauwkeurigheid")
                    .font(.system(size: 12, weight: .medium))
                    .foregroundColor(.proatText2)
                progressDotsWithNumber(value: model.accuracy * 10)
            }
            .lineLimit(1)
            .fixedSize(horizontal: true, vertical: false)
        }
        .lineLimit(1)
    }

    private var descriptionSection: some View {
        Text(model.description)
            .font(ProatFont.klein)
            .foregroundColor(.proatText3)
            .lineLimit(2)
            .fixedSize(horizontal: false, vertical: true)
            .padding(.top, ProatSpacing.xs / 2)
    }
    
    private var progressSection: some View {
        Group {
            if isDownloading || isWarming {
                DownloadProgressView(
                    modelName: model.name,
                    downloadProgress: downloadProgress,
                    isOptimizing: isWarming && !isDownloading
                )
                .padding(.top, 8)
                .frame(maxWidth: .infinity, alignment: .leading)
            }
        }
    }
    
    private var actionSection: some View {
        HStack(spacing: ProatSpacing.xs) {
            if isCurrent {
                Text("Standaardmodel")
                    .font(.system(size: 12, weight: .medium))
                    .foregroundColor(.proatTeal)
            } else if isDownloaded {
                Button(action: setDefaultAction) {
                    Text("Als standaard instellen")
                        .font(.system(size: 12))
                }
                .buttonStyle(.bordered)
                .controlSize(.small)
            } else {
                Button(action: downloadAction) {
                    ProatPrimaryPillLabel(
                        title: isDownloading ? "Downloaden…" : "Downloaden",
                        systemImage: "arrow.down.circle"
                    )
                }
                .buttonStyle(.plain)
                .disabled(isDownloading)
            }

            if isDownloaded {
                Menu {
                    Button(action: deleteAction) {
                        Label("Model verwijderen", systemImage: "trash")
                    }

                    Button {
                        if let modelURL = modelURL {
                            NSWorkspace.shared.selectFile(modelURL.path, inFileViewerRootedAtPath: "")
                        }
                    } label: {
                        Label("Toon in Finder", systemImage: "folder")
                    }
                } label: {
                    Image(systemName: "ellipsis.circle")
                        .font(.system(size: 14))
                        .foregroundColor(.proatText2)
                }
                .menuStyle(.borderlessButton)
                .menuIndicator(.hidden)
                .frame(width: 20, height: 20)
            }
        }
    }
}

// MARK: - Imported Local Model (minimal UI)
struct ImportedWhisperModelCardView: View {
    let model: ImportedWhisperModel
    let isDownloaded: Bool
    let isCurrent: Bool
    let modelURL: URL?

    var deleteAction: () -> Void
    var setDefaultAction: () -> Void

    var body: some View {
        HStack(alignment: .top, spacing: ProatSpacing.m) {
            VStack(alignment: .leading, spacing: ProatSpacing.xs - 2) {
                HStack(alignment: .firstTextBaseline) {
                    Text(model.displayName)
                        .font(ProatFont.sectie)
                        .foregroundColor(.proatText1)
                    Spacer()
                }

                Text("Geïmporteerd lokaal model")
                    .font(ProatFont.klein)
                    .foregroundColor(.proatText3)
                    .lineLimit(2)
                    .fixedSize(horizontal: false, vertical: true)
                    .padding(.top, ProatSpacing.xs / 2)
            }
            .frame(maxWidth: .infinity, alignment: .leading)

            HStack(spacing: ProatSpacing.xs) {
                if isCurrent {
                    Text("Standaardmodel")
                        .font(.system(size: 12, weight: .medium))
                        .foregroundColor(.proatTeal)
                } else if isDownloaded {
                    Button(action: setDefaultAction) {
                        Text("Als standaard instellen")
                            .font(.system(size: 12))
                    }
                    .buttonStyle(.bordered)
                    .controlSize(.small)
                }

                if isDownloaded {
                    Menu {
                        Button(action: deleteAction) {
                            Label("Model verwijderen", systemImage: "trash")
                        }
                        Button {
                            if let modelURL = modelURL {
                                NSWorkspace.shared.selectFile(modelURL.path, inFileViewerRootedAtPath: "")
                            }
                        } label: {
                            Label("Toon in Finder", systemImage: "folder")
                        }
                    } label: {
                        Image(systemName: "ellipsis.circle")
                            .font(.system(size: 14))
                            .foregroundColor(.proatText2)
                    }
                    .menuStyle(.borderlessButton)
                    .menuIndicator(.hidden)
                    .frame(width: 20, height: 20)
                }
            }
        }
        .padding(ProatSpacing.m)
        .background(ProatModelCardBackground(isSelected: isCurrent))
    }
}


// MARK: - Proat model-kaart

/// Neutrale modelkaart in het proat-designsysteem.
/// Teal verschijnt alleen als de kaart het actieve/standaardmodel is.
struct ProatModelCardBackground: View {
    var isSelected: Bool

    var body: some View {
        RoundedRectangle(cornerRadius: ProatRadius.kaart, style: .continuous)
            .fill(isSelected ? Color.proatTealTint : Color.proatBgRaised)
            .overlay(
                RoundedRectangle(cornerRadius: ProatRadius.kaart, style: .continuous)
                    .stroke(isSelected ? Color.proatTeal : Color.proatBorder,
                            lineWidth: isSelected ? 1.5 : 1)
            )
            .shadow(color: .black.opacity(0.08), radius: 8, x: 0, y: 4)
    }
}

/// Primaire teal-actieknop (download / configureren) volgens designsysteem.
struct ProatPrimaryPillLabel: View {
    let title: String
    let systemImage: String

    var body: some View {
        HStack(spacing: ProatSpacing.xs / 2) {
            Text(title)
                .font(.system(size: 12, weight: .semibold))
            Image(systemName: systemImage)
                .font(.system(size: 12, weight: .semibold))
        }
        .foregroundColor(.white)
        .padding(.horizontal, ProatSpacing.s)
        .padding(.vertical, ProatSpacing.xs - 2)
        .background(
            Capsule().fill(LinearGradient.proatTeal)
        )
        .proatShadowRust()
    }
}

// MARK: - Helper Views and Functions

func progressDotsWithNumber(value: Double) -> some View {
    HStack(spacing: 4) {
        progressDots(value: value)
        Text(String(format: "%.1f", value))
            .font(.system(size: 10, weight: .medium, design: .monospaced))
            .foregroundColor(.proatText3)
    }
}

func progressDots(value: Double) -> some View {
    HStack(spacing: 2) {
        ForEach(0..<5) { index in
            Circle()
                .fill(index < Int(value / 2) ? performanceColor(value: value / 10) : Color.proatBorder)
                .frame(width: 6, height: 6)
        }
    }
}

func performanceColor(value: Double) -> Color {
    // Neutrale track, teal-vulling voor de meter (geen kleuren-soep).
    return .proatTeal
}
