import SwiftUI

private struct PageListItem: View {

    @Environment(\.language)
    private var language

    @ObservedObject
    var page: Page

    var body: some View {
        HStack {
            LocalizedPageListItem(page: page.localized(in: language))
            Spacer()
            if page.isExternalUrl {
                TextIndicator(text: "External")
            } else if page.isDraft {
                TextIndicator(text: "Draft", background: .yellow)
            } else {
                ForEach(page.missingContentLanguages, id: \.self) { language in
                    TextIndicator(text: language.shortText, background: Color.red)
                }
            }
        }
    }
}

private struct LocalizedPageListItem: View {

    @ObservedObject
    var page: LocalizedPage

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

struct PageListView: View {

    @Environment(\.language)
    private var language

    @EnvironmentObject
    private var selection: SelectedContent

    @EnvironmentObject
    private var content: Content

    @State
    private var searchString = ""

    init() { }

    private var filteredPages: [Page] {
        guard !searchString.isEmpty else {
            return content.pages
        }
        return content.pages.filter { $0.localized(in: language).title.contains(searchString) }
    }

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

#Preview {
    let content = Content.mock
    let selection = SelectedContent()
    PageListView()
        .environmentObject(content)
        .environmentObject(selection)
}
