import SwiftUI

struct AddPostView: View {

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

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

    @EnvironmentObject
    private var content: Content

    @Binding
    var selectedPost: Post?

    @State
    private var newPostId = ""

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

    private var idExists: Bool {
        !content.isNewIdForPost(newPostId)
    }

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

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

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

    private func addNewPost() {
        let post = Post(
            content: content,
            id: newPostId,
            isDraft: true,
            createdDate: .now,
            startDate: .now,
            endDate: nil,
            tags: [],
            german: .init(content: content, title: newPostId, text: ""),
            english: .init(content: content, title: newPostId, text: ""))
        content.posts.insert(post, at: 0)
        selectedPost = post
        dismissSheet()
    }

    private func dismissSheet() {
        dismiss()
    }
}

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