import SwiftUI
import SFSafeSymbols

struct TagSelectionView: View {

    @Binding
    var presented: Bool

    @Binding
    private var selected: [Tag]

    @Binding
    private var tags: [Tag]

    @Environment(\.language)
    private var language

    init(presented: Binding<Bool>, selected: Binding<[Tag]>, tags: Binding<[Tag]>) {
        self._presented = presented
        self._selected = selected
        self._tags = tags
    }

    var body: some View {
        VStack(spacing: 0) {
            List {
                Section("Selected tags") {
                    ForEach(selected) { tag in
                        HStack {
                            Image(systemSymbol: .minusCircleFill)
                                .foregroundStyle(.red)
                                .onTapGesture {
                                    deselect(tag: tag)
                                }
                            Text(tag.localized(in: language).name)
                        }
                    }
                    .onMove(perform: moveTag)
                }
                Section("Available tags") {
                    ForEach(tags.filter({ !selected.contains($0) })) { tag in
                        HStack {
                            Image(systemSymbol: .plusCircleFill)
                                .foregroundStyle(.green)
                            Text(tag.localized(in: language).name)
                            Spacer()
                        }
                        .contentShape(Rectangle())
                        .onTapGesture {
                            select(tag: tag)
                        }
                    }
                }
            }
            .frame(minHeight: 300)
            .padding()
            Button(action: dismiss) {
                Text("Save")
            }.padding()
        }
    }

    private func moveTag(from source: IndexSet, to destination: Int) {
        selected.move(fromOffsets: source, toOffset: destination)
    }

    private func deselect(tag: Tag) {
        guard let index = selected.firstIndex(of: tag) else {
            return
        }
        selected.remove(at: index)
    }

    private func select(tag: Tag) {
        selected.append(tag)
    }

    private func dismiss() {
        presented = false
    }
}

#Preview {
    TagSelectionView(
        presented: .constant(true),
        selected: .constant([
            Tag.Mock.hiking,
            Tag.Mock.nature
        ]),
        tags: .constant([
            Tag.Mock.sports,
            Tag.Mock.electronics
        ])
    )
}
