import SwiftUI

struct PagePickerView: View {

    @EnvironmentObject
    private var content: Content

    @Environment(\.language)
    private var language

    @Environment(\.dismiss)
    var dismiss

    @Binding var selectedPage: Page?

    @State
    private var newSelection: Page?

    init(selectedPage: Binding<Page?>) {
        self._selectedPage = selectedPage
        self.newSelection = selectedPage.wrappedValue
        // TODO: Fix assignment not working
    }

    var body: some View {
        VStack {
            Text("Select a page to link to")
            List(content.pages, selection: $newSelection) { page in
                let loc = page.localized(in: language)
                Text("\(loc.title) (\(page.identifier))")
                    .tag(page)
            }
            .frame(minHeight: 300)
            HStack {
                Button("Use selection") {
                    DispatchQueue.main.async {
                        self.selectedPage = self.newSelection
                        dismiss()
                    }
                }
                Button("Remove page", role: .destructive) {
                    DispatchQueue.main.async {
                        self.selectedPage = nil
                        dismiss()
                    }
                }
                Button("Cancel", role: .cancel) {
                    dismiss()
                }
            }
        }
        .navigationTitle("Pick a page")
        .padding()
    }
}

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