{% load static %}

<dialog
  id="new_scenario_modal"
  class="modal"
  x-data="{
    isSubmitting: false,
    error: null,
    scenarioType: 'empty',
    schemas: {},
    groupSchemas: {},
    loadingSchemas: false,
    formData: {
      name: '',
      description: '',
      dateYear: '',
      dateMonth: '',
      dateDay: '',
      scenarioType: 'empty',
      additionalInformation: {}
    },
    // Track form data from each schema renderer
    schemaFormData: {},

    validateYear(el) {
      if (el.value && el.value.length < 4) {
        el.value = new Date().getFullYear();
      }
    },

    async init() {
      try {
        this.loadingSchemas = true;
        // Ensure API client is available
        if (!window.AdditionalInformationApi) {
          throw new Error('Additional Information API client not loaded. Please refresh the page.');
        }

        // Use single API call to load schemas organized by groups
        const { schemas, groupSchemas } =
          await window.AdditionalInformationApi.loadSchemasWithGroups(['soil', 'sludge', 'sediment']);

        this.schemas = schemas;
        this.groupSchemas = groupSchemas;
      } catch (err) {
        this.error = err.message;
        console.error('Error loading schemas:', err);
      } finally {
        this.loadingSchemas = false;
      }
    },

    reset() {
      this.isSubmitting = false;
      this.error = null;
      this.scenarioType = 'empty';
      this.formData = {
        name: '',
        description: '',
        dateYear: '',
        dateMonth: '',
        dateDay: '',
        scenarioType: 'empty',
        additionalInformation: {}
      };
      this.schemaFormData = {};
    },

    setSchemaFormData(schemaName, data) {
      this.schemaFormData[schemaName] = data;
    },

    async submit() {
      if (!this.formData.name || this.formData.name.trim() === '') {
        this.error = 'Please enter a scenario name';
        return;
      }

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

      try {
        // Build scenario date
        let scenarioDate = this.formData.dateYear || '';
        if (this.formData.dateMonth && this.formData.dateMonth.trim() !== '') {
          scenarioDate += `-${parseInt(this.formData.dateMonth).toString().padStart(2, '0')}`;
          if (this.formData.dateDay && this.formData.dateDay.trim() !== '') {
            scenarioDate += `-${parseInt(this.formData.dateDay).toString().padStart(2, '0')}`;
          }
        }

        if (!scenarioDate || scenarioDate.trim() === '') {
          scenarioDate = 'No date';
        }

        // Collect additional information from schema forms
        const additionalInformation = [];
        const currentGroupSchemas = this.groupSchemas[this.scenarioType] || {};

        for (const schemaName in this.schemaFormData) {
          const data = this.schemaFormData[schemaName];
          // Only include if schema belongs to current group and has data
          if (currentGroupSchemas[schemaName] && data && Object.keys(data).length > 0) {
            // Check if data has any non-null/non-empty values
            const hasData = Object.values(data).some(val => {
              if (val === null || val === undefined || val === '') return false;
              if (typeof val === 'object' && val !== null) {
                // For interval objects, check if start or end has value
                if (val.start !== null && val.start !== undefined && val.start !== '') return true;
                if (val.end !== null && val.end !== undefined && val.end !== '') return true;
                return false;
              }
              return true;
            });

            if (hasData) {
              additionalInformation.push({
                type: schemaName,
                data: data
              });
            }
          }
        }

        // Build payload
        const payload = {
          name: this.formData.name.trim(),
          description: this.formData.description ? this.formData.description.trim() : '',
          scenario_date: scenarioDate,
          scenario_type: this.scenarioType === 'empty' ? 'Not specified' : this.scenarioType,
          additional_information: additionalInformation
        };

        const packageUuid = '{{ meta.current_package.uuid }}';

        // Use API client for scenario creation
        const result = await window.AdditionalInformationApi.createScenario(packageUuid, payload);

        // Close modal and redirect to new scenario
        document.getElementById('new_scenario_modal').close();
        window.location.href = result.url || `{{ meta.current_package.url }}/scenario/${result.uuid}`;
      } catch (err) {
        this.error = err.message;
      } finally {
        this.isSubmitting = false;
      }
    }
  }"
  @close="reset()"
  @schema-form-data-changed.window="setSchemaFormData($event.detail.schemaName, $event.detail.data)"
>
  <div class="modal-box max-w-3xl max-h-[90vh] overflow-y-auto">
    <!-- Header -->
    <h3 class="text-lg font-bold">New Scenario</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="alert alert-info mb-4">
        <span>
          Please enter name, description, and date of scenario. Date should be
          associated to the data, not the current date. For example, this could
          reflect the publishing date of a study. You can leave all fields but
          the name empty and fill them in later.
          <a
            target="_blank"
            href="https://wiki.envipath.org/index.php/scenario"
            class="link"
            >wiki &gt;&gt;</a
          >
        </span>
      </div>

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

      <!-- 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>

      <!-- Form fields -->
      <template x-if="!loadingSchemas">
        <div>
          <div class="form-control mb-3">
            <label class="label" for="scenario-name">
              <span class="label-text">Name</span>
            </label>
            <input
              id="scenario-name"
              type="text"
              class="input input-bordered w-full"
              placeholder="Name"
              x-model="formData.name"
              required
            />
          </div>

          <div class="form-control mb-3">
            <label class="label" for="scenario-description">
              <span class="label-text">Description</span>
            </label>
            <input
              id="scenario-description"
              type="text"
              class="input input-bordered w-full"
              placeholder="Description"
              x-model="formData.description"
            />
          </div>

          <div class="form-control mb-3">
            <label class="label">
              <span class="label-text">Date</span>
            </label>
            <div class="flex gap-2">
              <input
                type="number"
                class="input input-bordered w-24"
                placeholder="YYYY"
                max="{% now 'Y' %}"
                x-model="formData.dateYear"
                @blur="validateYear($el)"
              />
              <input
                type="number"
                min="1"
                max="12"
                class="input input-bordered w-20"
                placeholder="MM"
                x-model="formData.dateMonth"
              />
              <input
                type="number"
                min="1"
                max="31"
                class="input input-bordered w-20"
                placeholder="DD"
                x-model="formData.dateDay"
              />
            </div>
          </div>

          <div class="form-control mb-3">
            <label class="label">
              <span class="label-text">Scenario Type</span>
            </label>
            <div role="tablist" class="tabs tabs-border">
              <button
                type="button"
                role="tab"
                class="tab"
                :class="{ 'tab-active': scenarioType === 'empty' }"
                @click="scenarioType = 'empty'"
              >
                Empty Scenario
              </button>
              <button
                type="button"
                role="tab"
                class="tab"
                :class="{ 'tab-active': scenarioType === 'soil' }"
                @click="scenarioType = 'soil'"
              >
                Soil Data
              </button>
              <button
                type="button"
                role="tab"
                class="tab"
                :class="{ 'tab-active': scenarioType === 'sludge' }"
                @click="scenarioType = 'sludge'"
              >
                Sludge Data
              </button>
              <button
                type="button"
                role="tab"
                class="tab"
                :class="{ 'tab-active': scenarioType === 'sediment' }"
                @click="scenarioType = 'sediment'"
              >
                Water-Sediment System Data
              </button>
            </div>
          </div>

          <!-- Schema forms for each scenario type -->
          <template x-if="scenarioType === 'soil'">
            <div class="space-y-4 mt-4">
              <template
                x-for="(rjsf, schemaName) in groupSchemas.soil"
                :key="schemaName"
              >
                <div
                  x-data="schemaRenderer({
                    rjsf: rjsf,
                    mode: 'edit'
                  })"
                  x-init="await init();
                  const currentSchemaName = schemaName;
                  $watch('data', (value) => {
                    $dispatch('schema-form-data-changed', { schemaName: currentSchemaName, data: value });
                  }, { deep: true })"
                >
                  {% include "components/schema_form.html" %}
                </div>
              </template>
            </div>
          </template>

          <template x-if="scenarioType === 'sludge'">
            <div class="space-y-4 mt-4">
              <template
                x-for="(rjsf, schemaName) in groupSchemas.sludge"
                :key="schemaName"
              >
                <div
                  x-data="schemaRenderer({
                    rjsf: rjsf,
                    mode: 'edit'
                  })"
                  x-init="await init();
                  const currentSchemaName = schemaName;
                  $watch('data', (value) => {
                    $dispatch('schema-form-data-changed', { schemaName: currentSchemaName, data: value });
                  }, { deep: true })"
                >
                  {% include "components/schema_form.html" %}
                </div>
              </template>
            </div>
          </template>

          <template x-if="scenarioType === 'sediment'">
            <div class="space-y-4 mt-4">
              <template
                x-for="(rjsf, schemaName) in groupSchemas.sediment"
                :key="schemaName"
              >
                <div
                  x-data="schemaRenderer({
                    rjsf: rjsf,
                    mode: 'edit'
                  })"
                  x-init="await init();
                  const currentSchemaName = schemaName;
                  $watch('data', (value) => {
                    $dispatch('schema-form-data-changed', { schemaName: currentSchemaName, data: value });
                  }, { deep: true })"
                >
                  {% include "components/schema_form.html" %}
                </div>
              </template>
            </div>
          </template>
        </div>
      </template>
    </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()"
        :disabled="isSubmitting || 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>
