<dialog
  id="manage_api_token_modal"
  class="modal"
  x-data="{
    isSubmitting: false,
    newToken: '',
    tokens: [],

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

    async requestToken() {
      this.isSubmitting = true;
      const form = document.getElementById('request_api_token_form');
      const formData = new FormData(form);

      try {
        const response = await fetch('{{ meta.user.url }}', {
          method: 'POST',
          body: new URLSearchParams(formData)
        });
        const data = await response.json();
        this.newToken = data.raw_token;
      } catch (error) {
        console.error('Error requesting token:', error);
      } finally {
        this.isSubmitting = false;
      }
    },

    async deleteToken(form) {
      const formData = new FormData(form);
      try {
        await fetch(form.action, {
          method: 'POST',
          body: new URLSearchParams(formData)
        });
        form.closest('.token-item').remove();
      } catch (error) {
        console.error('Error deleting token:', error);
      }
    }
  }"
  @close="reset()"
>
  <div class="modal-box">
    <!-- Header -->
    <h3 class="text-lg font-bold">Manage API Token</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">
      <p class="mb-4">
        Requesting a Token will invalidate all potential existing tokens. The
        new token will only be shown once, so ensure to store it in a secure
        place.
      </p>

      <form id="request_api_token_form" accept-charset="UTF-8" method="post">
        {% csrf_token %}
        <div class="form-control mb-3">
          <label class="label" for="token-name">
            <span class="label-text">Name</span>
          </label>
          <input
            type="text"
            id="token-name"
            class="input input-bordered w-full"
            name="name"
            placeholder="Generic Token for {{ meta.user.username }}"
          />
        </div>
        <div class="form-control mb-3">
          <label class="label" for="valid-for">
            <span class="label-text">Valid for (in days)</span>
          </label>
          <input
            type="number"
            id="valid-for"
            class="input input-bordered w-full"
            name="valid-for"
            value="90"
          />
        </div>
        <input type="hidden" name="hidden" value="request-api-token" />
      </form>

      <!-- New Token Display -->
      <div x-show="newToken" x-cloak class="alert alert-success mb-4">
        <div class="w-full">
          <span class="font-bold">New Token:</span>
          <pre
            class="mt-2 p-2 bg-base-200 rounded overflow-x-auto"
            x-text="newToken"
          ></pre>
        </div>
      </div>

      <!-- Existing Tokens -->
      <div class="space-y-2">
        {% for t in tokens %}
          <div class="token-item">
            <form
              id="delete-token-{{ forloop.counter0 }}"
              accept-charset="UTF-8"
              action="{{ meta.user.url }}"
              method="post"
            >
              {% csrf_token %}
              <div class="join w-full">
                <input type="hidden" name="hidden" value="delete" />
                <input type="hidden" name="token-id" value="{{ t.pk }}" />
                <input
                  type="text"
                  class="input input-bordered join-item w-full"
                  value="{{ t.name|safe }}"
                  disabled
                />
                <button
                  type="button"
                  class="btn btn-error join-item"
                  @click="deleteToken($el.closest('form'))"
                >
                  Delete
                </button>
              </div>
            </form>
          </div>
        {% endfor %}
      </div>
    </div>

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

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