import SwiftUI
import SFSafeSymbols

protocol InsertableCommand: View {

    static var title: String { get }

    static var sheetTitle: String { get }

    static var icon: SFSymbol { get }

    init(command: Binding<String?>)
}

struct InsertableCommandSheet<Presented>: View where Presented: InsertableCommand {

    @Environment(\.dismiss)
    var dismiss

    @State
    private var error: String? = nil

    @State
    private var command: String?

    init() { }

    var body: some View {
        VStack {
            Text(Presented.sheetTitle)
                .font(.title)
            Presented(command: $command)
            if let error {
                Text(error)
                    .foregroundStyle(.red)
            }
            HStack {
                Button("Copy to clipboard", action: copyToClipboard)
                    .padding()
                Button("Cancel") {
                    dismiss()
                }.padding()
            }
        }
        .padding()
    }

    func copyToClipboard() {
        guard let command else {
            error = "Not all fields set"
            return
        }
        defer { dismiss() }

        let pasteboard = NSPasteboard.general
        pasteboard.clearContents()
        pasteboard.setString(command, forType: .string)
    }
}
