{% load static %}
<!-- Add Additional Information -->
<dialog
  id="add_scenario_additional_information_modal"
  class="modal"
  x-data="{
    isSubmitting: false,
    selectedType: '',
    schemas: {},
    loadingSchemas: false,
    error: null,
    formData: null,  // Store reference to form data
    formRenderKey: 0,  // Counter to force form re-render
    existingTypes: [],  // Track existing additional information types

    // Get sorted unique schema names for dropdown, excluding already-added types
    get sortedSchemaNames() {
      const names = Object.keys(this.schemas);
      // Remove duplicates, exclude existing types, and sort alphabetically by display title
      const unique = [...new Set(names)];
      const available = unique.filter(name =>
        !this.existingTypes.includes(name) || this.schemas[name]?.schema?.['x-repeatable']
      );
      return available.sort((a, b) => {
        const titleA = (this.schemas[a]?.schema?.['x-title'] || a).toLowerCase();
        const titleB = (this.schemas[b]?.schema?.['x-title'] || b).toLowerCase();
        return titleA.localeCompare(titleB);
      });
    },

    async init() {
      // Watch for selectedType changes
      this.$watch('selectedType', (value) => {
        // Reset formData when type changes and increment key to force re-render
        this.formData = null;
        this.formRenderKey++;
        // Clear previous errors
        this.error = null;
        Alpine.store('validationErrors').clearErrors(); // No context - clears all
      });

      // Load schemas and existing items
      try {
        this.loadingSchemas = true;
        const scenarioUuid = '{{ scenario.uuid }}';
        const [schemasRes, itemsRes] = await Promise.all([
          fetch('/api/v1/information/schema/'),
          fetch(`/api/v1/scenario/${scenarioUuid}/information/`)
        ]);

        if (!schemasRes.ok) throw new Error('Failed to load schemas');
        if (!itemsRes.ok) throw new Error('Failed to load existing items');

        this.schemas = await schemasRes.json();
        const items = await itemsRes.json();

        // Get unique existing types (normalize to lowercase)
        this.existingTypes = [...new Set(items.map(item => item.type.toLowerCase()))];
      } catch (err) {
        this.error = err.message;
      } finally {
        this.loadingSchemas = false;
      }
    },

    reset() {
      this.isSubmitting = false;
      this.selectedType = '';
      this.error = null;
      this.formData = null;
      Alpine.store('validationErrors').clearErrors(); // No context - clears all
    },

    setFormData(data) {
      this.formData = data;
    },

    async submit() {
      if (!this.selectedType) return;

      const payload = window.AdditionalInformationApi.sanitizePayload(this.formData);

      // Validate that form has data
      if (!payload || Object.keys(payload).length === 0) {
        this.error = 'Please fill in at least one field';
        return;
      }

      this.isSubmitting = true;
      this.error = null;

      try {
        const scenarioUuid = '{{ scenario.uuid }}';
        await window.AdditionalInformationApi.createItem(
          scenarioUuid,
          this.selectedType,
          payload
        );

        // Close modal and reload page to show new item
        document.getElementById('add_scenario_additional_information_modal').close();
        window.location.reload();
      } catch (err) {
        if (err.isValidationError && err.fieldErrors) {
          // No context for add modal - simple flat errors
          Alpine.store('validationErrors').setErrors(err.fieldErrors);
          this.error = err.message || 'Please correct the errors in the form';
        } else {
          this.error = err.message || 'An error occurred. Please try again.';
        }
      } finally {
        this.isSubmitting = false;
      }
    }
  }"
  @close="reset()"
  @form-data-ready="formData = $event.detail"
>
  <div class="modal-box max-w-2xl">
    <!-- Header -->
    <h3 class="text-lg font-bold">Add Additional Information</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">
      <!-- Loading state -->
      <template x-if="loadingSchemas">
        <div class="flex items-center justify-center p-4">
          <span class="loading loading-spinner loading-md"></span>
        </div>
      </template>

      <!-- Error state -->
      <template x-if="error">
        <div class="alert alert-error mb-4">
          <span x-text="error"></span>
        </div>
      </template>

      <!-- Schema selection -->
      <template x-if="!loadingSchemas">
        <div>
          <div class="form-control mb-4">
            <label class="label" for="select-additional-information-type">
              <span class="label-text">Select the type to add</span>
            </label>
            <select
              id="select-additional-information-type"
              class="select select-bordered w-full"
              x-model="selectedType"
            >
              <option value="" selected disabled>Select the type to add</option>
              <template x-for="name in sortedSchemaNames" :key="name">
                <option
                  :value="name"
                  x-text="(schemas[name].schema && (schemas[name].schema['x-title'] || schemas[name].schema.title)) || name"
                ></option>
              </template>
            </select>
          </div>

          <!-- Form renderer for selected type -->
          <!-- Use unique key per type to force re-render -->
          <template x-for="renderKey in [formRenderKey]" :key="renderKey">
            <div x-show="selectedType && schemas[selectedType]">
              <div
                x-data="schemaRenderer({
                  rjsf: schemas[selectedType],
                  mode: 'edit'
                  // No context - single form, backward compatible
                })"
                x-init="await init(); $dispatch('form-data-ready', data)"
              >
                {% include "components/schema_form.html" %}
              </div>
            </div>
          </template>
        </div>
      </template>
    </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 || !selectedType || loadingSchemas"
      >
        <span x-show="!isSubmitting">Add</span>
        <span
          x-show="isSubmitting"
          class="loading loading-spinner loading-sm"
        ></span>
        <span x-show="isSubmitting">Adding...</span>
      </button>
    </div>
  </div>

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