import SwiftUI

private struct PostListItem: View {

    @Environment(\.language)
    private var language

    @ObservedObject
    var post: Post

    var body: some View {
        HStack {
            LocalizedPostListItem(id: post.identifier, post: post.localized(in: language))
            if post.isDraft {
                TextIndicator(text: "Draft", background: .yellow)
            } else {
                if post.german.text.isEmpty {
                    TextIndicator(text: "DE", background: .yellow)
                }
                if post.english.text.isEmpty {
                    TextIndicator(text: "EN", background: .yellow)
                }
            }
        }
    }
}

private struct LocalizedPostListItem: View {

    let id: String

    @ObservedObject
    var post: LocalizedPost

    var body: some View {
        HStack {
            Text(post.title ?? id)
                .lineLimit(1)
            Spacer()
        }
    }
}

struct PostListView: View {

    @Environment(\.language)
    private var language

    @EnvironmentObject
    private var content: Content

    @EnvironmentObject
    private var selection: SelectedContent

    @State
    private var searchString = ""

    init() { }

    private var filteredPosts: [Post] {
        guard !searchString.isEmpty else {
            return content.posts
        }
        return content.posts.filter { $0.contains(searchString) }
    }

    private var filteredAndSortedPosts: [Post] {
        filteredPosts.sortedByStartDateAndId()
    }

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