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)
    }
}

struct PageListView: View {

    @Environment(\.language)
    private var language

    @EnvironmentObject
    private var content: Content

    @Binding
    private var selectedPage: Page?

    @State
    private var searchString = ""

    init(selectedPage: Binding<Page?>) {
        self._selectedPage = selectedPage
    }

    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)
            List(filteredPages, selection: $selectedPage) { page in
                PageListItem(page: page)
                    .tag(page)
            }
        }
        .onAppear {
            if selectedPage == nil {
                selectedPage = content.pages.first
            }
        }
    }
}

#Preview {
    PageListView(selectedPage: .constant(nil))
        .environmentObject(Content.mock)
}
