import SwiftUI

private struct PostListItem: View {

    @Environment(\.language)
    private var language

    @ObservedObject
    var post: Post

    var body: some View {
        HStack {
            LocalizedPostListItem(id: post.id, 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)
            Spacer()
        }
    }
}

struct PostListView: View {

    @Environment(\.language)
    private var language

    @EnvironmentObject
    private var content: Content

    @Binding
    private var selectedPost: Post?

    @State
    private var searchString = ""

    init(selectedPost: Binding<Post?>) {
        self._selectedPost = selectedPost
    }

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

    private var filteredAndSortedPosts: [Post] {
        filteredPosts.sorted(ascending: false) { $0.startDate }
    }

    var body: some View {
        VStack {
            TextField("", text: $searchString, prompt: Text("Search"))
                .textFieldStyle(.roundedBorder)
                .padding(.horizontal, 8)
            List(filteredAndSortedPosts, selection: $selectedPost) { post in
                PostListItem(post: post)
                    .tag(post)
            }
        }.onAppear {
            if selectedPost == nil {
                selectedPost = content.posts.first
            }
        }
    }
}
