import SwiftUI

struct LabelEditingView: View {

    @Binding
    var label: ContentLabel

    @State
    private var showIconPicker: Bool = false

    let scale: CGFloat

    init(label: Binding<ContentLabel>, scale: CGFloat = 1.0) {
        self._label = label
        self.scale = scale
    }

    var body: some View {
        HStack {
            Button(action: { showIconPicker = true }) {
                PageIconView(icon: label.icon)
                    .frame(maxWidth: 16, maxHeight: 16)
                    .scaleEffect(scale)
                    .contentShape(Rectangle())
            }
            .buttonStyle(.plain)
            TextField("", text: $label.value)
                .textFieldStyle(.plain)
        }
        .sheet(isPresented: $showIconPicker) {
            LabelIconSelectionView(selected: $label.icon)
        }
    }
}

private struct LabelIconSelectionView: View {

    @Environment(\.dismiss)
    var dismiss

    @Binding
    var selected: PageIcon

    var body: some View {
        VStack {
            List(PageIcon.allCases, id: \.rawValue) { icon in
                HStack {
                    Image(systemSymbol: selected == icon ? .checkmarkCircleFill : .circle)
                    PageIconView(icon: icon)
                        .frame(maxWidth: 20, maxHeight: 20)
                    Text(icon.name)
                    Spacer()
                }
                .contentShape(Rectangle())
                .onTapGesture {
                    selected = icon
                    dismiss()
                }
            }.frame(minHeight: 300)
            Button("Done") {
                dismiss()
            }
        }.padding()
    }
}
