{% load static %}

<dialog
  id="set_aliases_modal"
  class="modal"
  x-data="{
    isSubmitting: false,
    aliases: [{% for alias in current_object.aliases %}'{{ alias|escapejs }}'{% if not forloop.last %},{% endif %}{% endfor %}],
    newAlias: '',
    errorMessage: '',

    reset() {
      this.isSubmitting = false;
      this.errorMessage = '';
    },

    addAlias() {
      const aliasText = this.newAlias.trim();
      if (aliasText === '') return;

      // Check for duplicates (case-insensitive)
      const exists = this.aliases.some(
        a => a.toLowerCase() === aliasText.toLowerCase()
      );

      if (!exists) {
        this.aliases.push(aliasText);
      }

      this.newAlias = '';
    },

    removeAlias(index) {
      this.aliases.splice(index, 1);
    },

    handleKeypress(e) {
      if (e.key === 'Enter') {
        e.preventDefault();
        this.addAlias();
      }
    },

    handleBlur() {
      if (this.newAlias.trim() !== '') {
        this.addAlias();
      }
    },

    async submit() {
      this.isSubmitting = true;
      this.errorMessage = '';

      const formData = new URLSearchParams();
      if (this.aliases.length === 0) {
        formData.append('aliases', '');
      } else {
        this.aliases.forEach(alias => {
          formData.append('aliases', alias);
        });
      }

      try {
        const response = await fetch('{{ current_object.url }}', {
          method: 'POST',
          headers: {
            'Content-Type': 'application/x-www-form-urlencoded',
            'X-CSRFToken': document.querySelector('[name=csrfmiddlewaretoken]').value
          },
          body: formData
        });

        if (response.ok) {
          const data = await response.json();
          window.location.href = data.success;
        } else {
          this.errorMessage = 'Setting aliases failed!';
        }
      } catch (error) {
        this.errorMessage = 'Setting aliases failed!';
      } finally {
        this.isSubmitting = false;
      }
    }
  }"
  @close="reset()"
>
  <div class="modal-box max-w-4xl">
    <!-- Header -->
    <h3 class="text-lg font-bold">
      Set Aliases for {{ current_object.name|safe }}
    </h3>

    <!-- Close button (X) -->
    <form method="dialog">
      <button
        class="btn btn-sm btn-circle btn-ghost absolute top-2 right-2"
        :disabled="isSubmitting"
      >
        ✕
      </button>
    </form>

    <!-- Body -->
    <div class="py-4">
      <div class="form-control">
        <label class="label">
          <span class="label-text">Aliases:</span>
        </label>
        <div
          class="flex flex-wrap items-center gap-1 p-2 border border-base-300 rounded-lg bg-base-100 min-h-[38px] cursor-text"
          @click="$refs.aliasInput.focus()"
        >
          <template x-for="(alias, index) in aliases" :key="index">
            <span class="badge badge-info gap-1 py-3">
              <span x-text="alias"></span>
              <button
                type="button"
                class="btn btn-ghost btn-xs p-0 h-auto min-h-0"
                @click.stop="removeAlias(index)"
              >
                ✕
              </button>
            </span>
          </template>
          <input
            type="text"
            x-ref="aliasInput"
            x-model="newAlias"
            class="flex-1 min-w-[120px] border-none outline-none bg-transparent text-sm"
            placeholder="Add Alias..."
            @keypress="handleKeypress($event)"
            @blur="handleBlur()"
          />
        </div>
      </div>

      <!-- Error Message -->
      <div x-show="errorMessage" x-cloak class="alert alert-error mt-4">
        <span x-text="errorMessage"></span>
      </div>
    </div>

    <!-- Footer -->
    <div class="modal-action">
      <button
        type="button"
        class="btn"
        onclick="this.closest('dialog').close()"
        :disabled="isSubmitting"
      >
        Close
      </button>
      <button
        type="button"
        class="btn btn-primary"
        @click="submit()"
        :disabled="isSubmitting"
      >
        <span x-show="!isSubmitting">Submit</span>
        <span
          x-show="isSubmitting"
          class="loading loading-spinner loading-sm"
        ></span>
        <span x-show="isSubmitting">Submitting...</span>
      </button>
    </div>
  </div>

  <!-- Backdrop -->
  <form method="dialog" class="modal-backdrop">
    <button :disabled="isSubmitting">close</button>
  </form>
</dialog>
