import SwiftUI

struct AddPageView: View {

    @Environment(\.dismiss)
    private var dismiss: DismissAction

    @Environment(\.language)
    private var language: ContentLanguage

    @EnvironmentObject
    private var content: Content

    @Binding
    var selectedPage: Page?

    @State
    private var newPageId = ""

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

    private var idExists: Bool {
        !content.isNewIdForPage(newPageId)
    }

    private var isInvalidId: Bool {
        !content.isValidIdForTagOrPageOrPost(newPageId)
    }

    var body: some View {
        VStack {
            Text("New page")
                .font(.headline)

            TextField("", text: $newPageId)
                .textFieldStyle(.roundedBorder)
                .frame(maxWidth: 350)
            if newPageId.isEmpty {
                Text("Enter the id of the new page to create")
                    .foregroundStyle(.secondary)
            } else if isInvalidId {
                Text("The id contains invalid characters")
                    .foregroundStyle(Color.red)
            } else if idExists {
                Text("A page with the same id already exists")
                    .foregroundStyle(Color.red)
            } else {
                Text("Create a new page with the id")
                    .foregroundStyle(.secondary)
            }
            HStack {
                Button(role: .cancel, action: dismissSheet) {
                    Text("Cancel")
                }
                Button(action: addNewPage) {
                    Text("Create")
                }
                .disabled(isInvalidId || idExists)
            }
        }
        .padding()
    }

    private func addNewPage() {
        let page = Page(
            content: content,
            id: newPageId,
            externalLink: nil,
            isDraft: true,
            createdDate: .now,
            hideDate: false,
            startDate: .now,
            endDate: nil,
            german: .init(content: content,
                          urlString: "seite",
                          title: "Ein Titel"),
            english: .init(content: content,
                           urlString: "page",
                           title: "A Title"),
            tags: [])
        content.add(page)
        selectedPage = page
        dismissSheet()
    }

    private func dismissSheet() {
        dismiss()
    }
}

#Preview {
    AddPageView(selected: .constant(nil))
        .environmentObject(Content.mock)
}
