import SwiftUI
import SFSafeSymbols

struct InsertableGallery: View, InsertableCommandView {

    static let title = "Gallery"

    static let sheetTitle = "Insert an image gallery"

    static let icon: SFSymbol = .photoStack

    final class Model: InsertableCommandModel {

        @Published
        var images: [FileResource] = []

        var isReady: Bool {
            !images.isEmpty
        }

        init() {

        }

        var command: String? {
            guard !images.isEmpty else {
                return nil
            }
            return (
                ["```\(GalleryBlock.blockId)"] +
                images.map { $0.identifier } +
                ["```"]
            ).joined(separator: "\n")
        }
    }

    @Environment(\.colorScheme)
    private var colorScheme

    @ObservedObject
    private var model: Model

    @State
    private var showImagePicker = false

    init(model: Model) {
        self.model = model
    }

    var body: some View {
        VStack(spacing: 2) {
            ScrollView(.horizontal) {
                HStack(alignment: .center, spacing: 8) {
                    ForEach(model.images) { image in
                        PostImageView(image: image)
                    }
                }
            }
            Button("Select images", action: { showImagePicker = true })
            .padding(.vertical, 2)
        }
        .sheet(isPresented: $showImagePicker) {
            MultiFileSelectionView(
                selectedFiles: $model.images,
                allowedType: .image)
        }
    }
}
