import SwiftUI

struct TagPickerView: View {

    @EnvironmentObject
    private var content: Content

    @Environment(\.language)
    private var language

    @Environment(\.dismiss)
    var dismiss

    @Binding var selectedTag: Tag?

    @State
    private var newSelection: Tag?

    init(selectedTag: Binding<Tag?>) {
        self._selectedTag = selectedTag
        self.newSelection = selectedTag.wrappedValue
        // TODO: Fix assignment not working
    }

    var body: some View {
        VStack {
            Text("Select a tag to link to")
            List(content.tags, selection: $newSelection) { tag in
                let loc = tag.localized(in: language)
                Text("\(loc.title) (\(tag.identifier))")
                    .tag(tag)
            }
            .frame(minHeight: 300)
            HStack {
                Button("Use selection") {
                    DispatchQueue.main.async {
                        self.selectedTag = self.newSelection
                        dismiss()
                    }
                }
                Button("Remove tag", role: .destructive) {
                    DispatchQueue.main.async {
                        self.selectedTag = nil
                        dismiss()
                    }
                }
                Button("Cancel", role: .cancel) {
                    dismiss()
                }
            }
        }
        .navigationTitle("Pick a tag")
        .padding()
    }
}

#Preview {
    TagPickerView(selectedTag: .constant(nil))
        .environmentObject(Content.mock)
}
