import SwiftUI

struct AddTagView: View {

    @Environment(\.language)
    private var language

    @EnvironmentObject
    private var content: Content

    @Environment(\.dismiss)
    private var dismiss

    @Binding
    var selectedTag: Tag?

    @State
    private var newId = ""

    init(selected: Binding<Tag?>) {
        self._selectedTag = selected
    }

    private var idExists: Bool {
        !content.isNewIdForTag(newId)
    }

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

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

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

    private func addNewTag() {
        let tag = Tag(
            content: content,
            id: newId,
            isVisible: true,
            german: .init(content: content, urlComponent: newId, name: newId),
            english: .init(content: content, urlComponent: "\(newId)-en", name: "\(newId)-en"))
        // Add to top of the list, and resort when changing the name
        content.tags.insert(tag, at: 0)
        selectedTag = tag
        dismiss()
    }

    private func dismissSheet() {
        dismiss()
    }
}
