import SwiftUI
import SFSafeSymbols

struct InsertableImage: View, InsertableCommand {

    static let title = "Image"

    static let sheetTitle = "Insert image"

    static let icon: SFSymbol = .photo

    @State
    private var selectedImage: FileResource?

    @State
    private var caption: String? = ""

    @Binding
    private var command: String?

    init(command: Binding<String?>) {
        self._command = command
    }

    var body: some View {
        VStack {
            FilePropertyView(
                title: "Image",
                footer: "Select the image to insert",
                selectedFile: $selectedImage,
                allowedType: .image)
            OptionalStringPropertyView(
                title: "Caption",
                text: $caption,
                prompt: "Image Caption",
                footer: "The caption to show on the fullscreen image")
        }
        .onChange(of: caption) { updateCommand() }
        .onChange(of: selectedImage) { updateCommand() }
    }

    func updateCommand() {
        command = currentCommand
    }

    private var currentCommand: String? {
        guard let selectedImage else {
            return nil
        }
        guard let caption else {
            return "![image](\(selectedImage.id))"
        }
        return "![image](\(selectedImage.id);\(caption))"
    }
}
