import SwiftUI

struct TagContentView: View {

    @ObservedObject
    var tag: Tag

    @Environment(\.language)
    private var language

    @EnvironmentObject
    private var content: Content

    @State
    private var showPageSelection = false

    @State
    private var showPostSelection = false

    var selectedPages: [Page] {
        content.pages.filter { $0.tags.contains(tag) }
    }

    var selectedPosts: [Post] {
        content.posts.filter { $0.contains(tag) }
    }

    var body: some View {
        List {
            Section("Pages") {
                ForEach(selectedPages) { page in
                    Text(page.localized(in: language).title)
                }
                Button(action: { showPageSelection = true }) {
                    Text("Select pages")
                }
                .buttonStyle(.plain)
                .foregroundStyle(Color.blue)
            }
            Section("Posts") {
                ForEach(selectedPosts) { post in
                    Text(post.title(in: language))
                }
                Button(action: { showPostSelection = true }) {
                    Text("Select posts")
                }
                .buttonStyle(.plain)
                .foregroundStyle(Color.blue)
            }
        }
        .sheet(isPresented: $showPageSelection) {
            PageTagAssignmentView(tag: tag)
        }
        .sheet(isPresented: $showPostSelection) {
            PostTagAssignmentView(tag: tag)
        }
    }
}

extension TagContentView: MainContentView {

    init(item: Tag) {
        self.tag = item
    }

    static let itemDescription = "a tag"
}

#Preview {
    TagContentView(tag: .Mock.hiking)
        .environmentObject(Content.mock)
}
