import SwiftUI

struct TagListView: View {

    @Environment(\.language)
    private var language

    @EnvironmentObject
    private var content: Content

    @EnvironmentObject
    private var selection: SelectedContent

    @State
    private var searchString = ""

    init() { }

    private var filteredTags: [Tag] {
        guard !searchString.isEmpty else {
            return content.tags
        }
        return content.tags.filter { $0.localized(in: language).name.contains(searchString) }
    }

    private var filteredAndSortedTags: [Tag] {
        filteredTags.sorted { $0.title(in: language) }
    }

    var body: some View {
        VStack {
            TextField("", text: $searchString, prompt: Text("Search"))
                .textFieldStyle(.roundedBorder)
                .padding(.horizontal, 8)
            ScrollView {
                LazyVStack(spacing: 0) {
                    ForEach(filteredAndSortedTags) { tag in
                        SelectableListItem(selected: selection.tag == tag) {
                            TagListItem(tag: tag.localized(in: language))
                        }
                        .id(tag)
                        .onTapGesture {
                            selection.tag = tag
                        }
                    }
                }.padding(.horizontal, 8)
            }
        }.onAppear {
            if selection.tag == nil, let first = content.tags.first {
                selection.tag = first
            }
        }
    }
}

private struct TagListItem: View {

    @ObservedObject
    var tag: LocalizedTag

    var body: some View {
        Text(tag.title)
            .lineLimit(1)
    }
}
