import SwiftUI
import AppKit
import Foundation
import SharedUIComponents

struct ServerInstallationOptionView: View {
    struct Metadata: Identifiable {
        let id = UUID()
        let label: String
        let value: String
        var monospaced: Bool = false
        var isLink: Bool = false
    }

    let title: String
    let iconSystemName: String
    let versionTag: String?
    let metadata: [Metadata]

    // State/control flags passed from parent
    let isExpanded: Bool
    let isInstalled: Bool
    let isInstalling: Bool
    let showUninstall: Bool

    // Layout constants
    let labelColumnWidth: CGFloat

    // Behavior closures supplied by parent
    let onToggleExpand: () -> Void
    let onInstall: () -> Void
    let onUninstall: () -> Void

    // Optional configuration JSON (already generated by parent) shown when expanded
    let config: [String: Any]?

    var body: some View {
        VStack(alignment: .leading, spacing: 4) {
            header
            if isExpanded, let config {
                configSection(config)
                    .transition(.opacity.combined(with: .scale(scale: 1, anchor: .top)))
            }
        }
        .padding(16)
        .background(
            RoundedRectangle(cornerRadius: 8)
                .fill(Color(nsColor: .controlBackgroundColor))
                .overlay(
                    RoundedRectangle(cornerRadius: 8)
                        .stroke(Color(nsColor: .separatorColor), lineWidth: 1)
                )
        )
        .animation(.easeInOut(duration: 0.2), value: isExpanded)
    }

    private var header: some View {
        VStack(alignment: .leading, spacing: 4) {
            HStack(alignment: .center, spacing: 8) {
                Label(title, systemImage: iconSystemName)
                    .font(.system(size: 14, weight: .medium))

                if let versionTag {
                    Text(versionTag)
                        .font(.system(size: 12, design: .monospaced))
                        .padding(.horizontal, 8)
                        .padding(.vertical, 2)
                        .background(Capsule().fill(Color.green.opacity(0.15)))
                }

                Spacer()

                Button(isExpanded ? "Hide" : "Preview") { onToggleExpand() }
                    .buttonStyle(.bordered)
                    .help(isExpanded ? "Hide configuration details" : "Preview configuration details")

                if showUninstall {
                    Button("Uninstall") { onUninstall() }
                        .buttonStyle(DestructiveButtonStyle())
                        .help("Uninstall this installed option")
                } else {
                    Button(action: onInstall) {
                        if isInstalling {
                            ProgressView().controlSize(.mini)
                        } else {
                            Text("Install")
                        }
                    }
                    .disabled(isInstalling)
                    .buttonStyle(.borderedProminent)
                    .help("Install this server using the selected option")
                }
            }

            // Metadata rows
            Group {
                ForEach(metadata) { item in
                    HStack(spacing: 6) {
                        Text(item.label)
                            .font(.system(size: 12, weight: .medium))
                            .foregroundColor(.secondary)
                            .frame(width: labelColumnWidth, alignment: .leading)

                        if item.isLink, let url = URL(string: item.value) {
                            Link(item.value, destination: url)
                                .font(.system(size: 12, design: item.monospaced ? .monospaced : .default))
                                .foregroundColor(.primary)
                                .textSelection(.enabled)
                        } else {
                            Text(item.value)
                                .font(.system(size: 12, design: item.monospaced ? .monospaced : .default))
                                .foregroundColor(.primary)
                                .textSelection(.enabled)
                        }
                    }
                }
            }
            .padding(.top, 6)
        }
    }

    private func configSection(_ config: [String: Any]) -> some View {
        VStack(alignment: .leading, spacing: 8) {
            Divider().padding(.vertical, 4)
            HStack {
                Text("Server Configuration")
                    .font(.system(size: 13, weight: .medium))
                Spacer()
            }
            configView(config)
        }
    }

    @ViewBuilder
    private func configView(_ config: [String: Any]) -> some View {
        ZStack(alignment: .topTrailing) {
            VStack(alignment: .leading, spacing: 8) {
                Text(formatConfigAsJSON(config))
                    .font(.system(.callout, design: .monospaced))
                    .textSelection(.enabled)
                    .frame(maxWidth: .infinity, alignment: .leading)
                    .fixedSize(horizontal: false, vertical: true)
                    .padding(.bottom, 2)
            }
            .padding(12)

            CopyButton {
                NSPasteboard.general.clearContents()
                NSPasteboard.general.setString(formatConfigAsJSON(config), forType: .string)
            }
            .padding(6)
            .help("Copy configuration to clipboard")
        }
        .background(
            RoundedRectangle(cornerRadius: 6)
                .fill(Color(nsColor: .textBackgroundColor).opacity(0.5))
        )
        .overlay(
            RoundedRectangle(cornerRadius: 6)
                .stroke(Color(nsColor: .separatorColor), lineWidth: 1)
        )
    }

    private func formatConfigAsJSON(_ config: [String: Any]) -> String {
        do {
            let data = try JSONSerialization.data(withJSONObject: config, options: [.prettyPrinted, .sortedKeys])
            return String(data: data, encoding: .utf8) ?? "{}"
        } catch { return "{}" }
    }
}
