{% load static %}
<dialog
  id="new_model_modal"
  class="modal"
  x-data="{
    isSubmitting: false,
    selectedType: '',
    buildAppDomain: false,
    requiresRulePackages: false,
    requiresDataPackages: false,
    additional_parameters: null,
    schemas: {},
    formRenderKey: 0,  // Counter to force form re-render
    formData: null,  // Store reference to form data

    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

        const select = this.$refs.typeSelect;
        const selectedOption = select.options[select.selectedIndex];

        this.requiresRulePackages = selectedOption.dataset.requires_rule_packages === 'True';
        this.requiresDataPackages = selectedOption.dataset.requires_data_packages === 'True';
        this.additional_parameters = selectedOption.dataset.additional_parameters;

        console.log(this.selectedType);
        console.log(this.schemas[this.additional_parameters]);
      });

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

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

        this.schemas = await schemasRes.json();
      } catch (err) {
        this.error = err.message;
      } finally {
        this.loadingSchemas = false;
      }
    },

    reset() {
      this.isSubmitting = false;
      this.selectedType = '';
      this.buildAppDomain = false;
      this.requiresRulePackages = false;
      this.requiresDataPackages = false;
      this.additional_parameters = null;
    },

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

    get showMlrr() {
      return this.selectedType === 'ml-relative-reasoning';
    },

    get showRbrr() {
      return this.selectedType === 'rule-based-relative-reasoning';
    },

    get showEnviformer() {
      return this.selectedType === 'enviformer';
    },

    get showRulePackages() {
      return this.requiresRulePackages;
    },

    get showDataPackages() {
      return this.requiresDataPackages;
    },

    submit(formId) {
      const form = document.getElementById(formId);

      // Remove previously injected inputs
      form.querySelectorAll('.dynamic-param').forEach(el => el.remove());

      // Add values from dynamic form into the html form
      if (this.formData) {
        Object.entries(this.formData).forEach(([key, value]) => {
          const input = document.createElement('input');
          input.type = 'hidden';
          input.name = key;
          input.value = value;
          input.classList.add('dynamic-param');

          form.appendChild(input);
        });
      }

      if (form && form.checkValidity()) {
        this.isSubmitting = true;
        form.submit();
      } else if (form) {
        form.reportValidity();
      }
    }
  }"
  @close="reset()"
  @form-data-ready="formData = $event.detail"
>
  <div class="modal-box max-w-3xl">
    <!-- Header -->
    <h3 class="text-lg font-bold">New Model</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">
      <form
        id="new_model_form"
        accept-charset="UTF-8"
        action="{{ meta.current_package.url }}/model"
        method="post"
      >
        {% csrf_token %}
        <div class="alert alert-info mb-4">
          <span>
            Create a new Model to limit the number of degradation products in
            the prediction. You just need to set a name and the packages you
            want the object to be based on. There are multiple types of models
            available. For additional information have a look at our
            <a
              target="_blank"
              href="https://wiki.envipath.org/index.php/relative-reasoning"
              class="link"
              >wiki &gt;&gt;</a
            >
          </span>
        </div>

        <!-- Name -->
        <div class="form-control mb-3">
          <label class="label" for="model-name">
            <span class="label-text">Name</span>
          </label>
          <input
            id="model-name"
            name="model-name"
            class="input input-bordered w-full"
            placeholder="Name"
            required
          />
        </div>

        <!-- Description -->
        <div class="form-control mb-3">
          <label class="label" for="model-description">
            <span class="label-text">Description</span>
          </label>
          <input
            id="model-description"
            name="model-description"
            class="input input-bordered w-full"
            placeholder="Description"
          />
        </div>

        <!-- Model Type -->
        <div class="form-control mb-3">
          <label class="label" for="model-type">
            <span class="label-text">Model Type</span>
          </label>
          <select
            id="model-type"
            name="model-type"
            class="select select-bordered w-full"
            x-model="selectedType"
            x-ref="typeSelect"
            required
          >
            <option value="" disabled selected>Select Model Type</option>
            {% for k, v in model_types.items %}
              <option
                value="{{ v.type }}"
                data-requires_rule_packages="{{ v.requires_rule_packages }}"
                data-requires_data_packages="{{ v.requires_data_packages }}"
                data-additional_parameters="{{ v.additional_parameters }}"
              >
                {{ k }}
              </option>
            {% endfor %}
          </select>
        </div>

        <!-- Rule Packages (MLRR, RBRR) -->
        <div class="form-control mb-3" x-show="showRulePackages" x-cloak>
          <label class="label" for="model-rule-packages">
            <span class="label-text">Rule Packages</span>
          </label>
          <select
            id="model-rule-packages"
            name="model-rule-packages"
            class="select select-bordered w-full h-32"
            multiple
          >
            <optgroup label="Reviewed Packages">
              {% for obj in meta.readable_packages %}
                {% if obj.reviewed %}
                  <option value="{{ obj.url }}">{{ obj.name|safe }}</option>
                {% endif %}
              {% endfor %}
            </optgroup>
            <optgroup label="Unreviewed Packages">
              {% for obj in meta.readable_packages %}
                {% if not obj.reviewed %}
                  <option value="{{ obj.url }}">{{ obj.name|safe }}</option>
                {% endif %}
              {% endfor %}
            </optgroup>
          </select>
          <label class="label">
            <span class="label-text-alt">Hold Ctrl/Cmd to select multiple</span>
          </label>
        </div>

        <!-- Data Packages (MLRR, RBRR, Enviformer) -->
        <div class="form-control mb-3" x-show="showDataPackages" x-cloak>
          <label class="label" for="model-data-packages">
            <span class="label-text">Data Packages</span>
          </label>
          <select
            id="model-data-packages"
            name="model-data-packages"
            class="select select-bordered w-full h-32"
            multiple
          >
            <optgroup label="Reviewed Packages">
              {% for obj in meta.readable_packages %}
                {% if obj.reviewed %}
                  <option value="{{ obj.url }}">{{ obj.name|safe }}</option>
                {% endif %}
              {% endfor %}
            </optgroup>
            <optgroup label="Unreviewed Packages">
              {% for obj in meta.readable_packages %}
                {% if not obj.reviewed %}
                  <option value="{{ obj.url }}">{{ obj.name|safe }}</option>
                {% endif %}
              {% endfor %}
            </optgroup>
          </select>
          <label class="label">
            <span class="label-text-alt">Hold Ctrl/Cmd to select multiple</span>
          </label>
        </div>

        <!-- Fingerprinter (MLRR) -->
        <div class="form-control mb-3" x-show="showMlrr" x-cloak>
          <label class="label" for="model-fingerprinter">
            <span class="label-text">Fingerprinter</span>
          </label>
          <select
            id="model-fingerprinter"
            name="model-fingerprinter"
            class="select select-bordered w-full h-32"
            multiple
          >
            <option value="MACCS" selected>MACCS Fingerprinter</option>
            {% if meta.enabled_features.PLUGINS and additional_descriptors %}
              <optgroup label="Additional Fingerprinter / Descriptor">
                {% for k, v in additional_descriptors.items %}
                  <option value="{{ v }}">{{ k }}</option>
                {% endfor %}
              </optgroup>
            {% endif %}
          </select>
          <label class="label">
            <span class="label-text-alt">Hold Ctrl/Cmd to select multiple</span>
          </label>
        </div>

        <!-- Threshold (MLRR, Enviformer) -->
        <div
          class="form-control mb-3"
          x-show="showMlrr || showEnviformer"
          x-cloak
        >
          <label class="label" for="model-threshold">
            <span class="label-text">Threshold</span>
          </label>
          <input
            type="number"
            min="0"
            max="1"
            step="0.05"
            value="0.5"
            id="model-threshold"
            name="model-threshold"
            class="input input-bordered w-full"
          />
        </div>

        <template x-if="!loadingSchemas">
          <template x-for="renderKey in [formRenderKey]" :key="renderKey">
            <div x-show="selectedType && schemas[additional_parameters]">
              <div
                x-data="schemaRenderer({
              rjsf: schemas[additional_parameters],
              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>
        </template>

        <!-- Applicability Domain (MLRR) -->
        {% if meta.enabled_features.APPLICABILITY_DOMAIN %}
          <div x-show="showMlrr" x-cloak>
            <div class="form-control mb-3">
              <label class="label cursor-pointer justify-start gap-3">
                <input
                  type="checkbox"
                  id="build-app-domain"
                  name="build-app-domain"
                  class="checkbox"
                  x-model="buildAppDomain"
                />
                <span class="label-text"
                  >Also build an Applicability Domain?</span
                >
              </label>
            </div>

            <div x-show="buildAppDomain" x-cloak class="ml-4 space-y-3">
              <div class="form-control">
                <label class="label" for="num-neighbors">
                  <span class="label-text">Number of Neighbors</span>
                </label>
                <input
                  id="num-neighbors"
                  name="num-neighbors"
                  type="number"
                  class="input input-bordered w-full"
                  value="5"
                  step="1"
                  min="0"
                  max="10"
                />
              </div>

              <div class="form-control">
                <label class="label" for="local-compatibility-threshold">
                  <span class="label-text">Local Compatibility Threshold</span>
                </label>
                <input
                  id="local-compatibility-threshold"
                  name="local-compatibility-threshold"
                  type="number"
                  class="input input-bordered w-full"
                  value="0.5"
                  step="0.01"
                  min="0"
                  max="1"
                />
              </div>

              <div class="form-control">
                <label class="label" for="reliability-threshold">
                  <span class="label-text">Reliability Threshold</span>
                </label>
                <input
                  id="reliability-threshold"
                  name="reliability-threshold"
                  type="number"
                  class="input input-bordered w-full"
                  value="0.5"
                  step="0.01"
                  min="0"
                  max="1"
                />
              </div>
            </div>
          </div>
        {% endif %}
      </form>
    </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="submit('new_model_form')"
        :disabled="isSubmitting || !selectedType || loadingSchemas"
      >
        <span x-show="!isSubmitting">Submit</span>
        <span
          x-show="isSubmitting"
          class="loading loading-spinner loading-sm"
        ></span>
        <span x-show="isSubmitting">Creating...</span>
      </button>
    </div>
  </div>

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