import SwiftUI

struct TagListView: View {

    @Environment(\.language)
    private var language

    @EnvironmentObject
    private var content: Content

    @Binding
    var selectedTag: Tag?

    @State
    private var searchString = ""

    init(selectedTag: Binding<Tag?>) {
        _selectedTag = selectedTag
    }

    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)
            List(filteredAndSortedTags, selection: $selectedTag) { tag in
                TagListItem(tag: tag.localized(in: language))
                    .tag(tag)
            }
        }.onAppear {
            if selectedTag == nil {
                selectedTag = content.tags.first
            }
        }
    }
}

private struct TagListItem: View {

    @ObservedObject
    var tag: LocalizedTag

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