import SwiftUI
import SFSafeSymbols

struct InsertableCommandSheet<Command>: View where Command: InsertableCommandView {

    @Environment(\.dismiss)
    var dismiss

    @State
    private var error: String? = nil

    @State
    private var isReady = false

    let model: Command.Model

    init() {
        model = .init()
    }

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

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

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