import { Controller } from "@hotwired/stimulus"

export default class extends Controller {
  static targets = ["dependentField", "providerField", "selectField"]

  connect() {
    if (this.selectFieldTarget.value) {
      this.toggleNewFieldSection();
    }
  }

  async initNewFieldSection() {
    console.log("--- in init async --- ")
    const selector = this.selectFieldTarget
    console.log(selector.textContent)
    console.log(selector.value)
    if (selector && selector.value && !selector.textContent.includes("Default")) {
      const sectionId = selector.value
      
      const response = await fetch(`/id_card/provider_sections/${sectionId}/get_section_data`);
      const templateSectionData = await response.json();

      this.#updateFields(templateSectionData)

      this.dependentFieldTarget.classList.remove("hidden");
    }
  }

  async toggleNewFieldSection() {
    console.log("--- in new field toggle --- ")
    const selector = this.selectFieldTarget
    const selectedOption = selector.options[selector.selectedIndex]
    const selectedValue = selectedOption.value
    const selectedLabel = selectedOption.textContent

    if (selectedValue && selectedLabel.includes("Default")) {
      this.dependentFieldTarget.classList.add("hidden");
    } else if (selectedValue) {
      let sectionId = selectedValue
      if (selectedValue.includes("new")) {
        sectionId = selectedValue.split('|')[1]
      }
      const response = await fetch(`/id_card/provider_sections/${sectionId}/get_section_data`);
      const sectionData = await response.json();

      this.#updateFields(sectionData)

      this.dependentFieldTarget.classList.remove("hidden");
    }

  }

  async #updateFields(templateSectionData) {
    const providerFieldTargetsList = this.providerFieldTargets
    console.log(templateSectionData)
    providerFieldTargetsList.forEach(function(formField) {
      const dbField = formField.id.replace('id_card_setup_provider_section_', '')
      const dbValue = templateSectionData[dbField]
      formField.value = dbValue;

    })




    // templateSectionData.forEach(function(data) {
    //   const targetElement = providerFieldTargetsList.find(
    //     (element) => element.dataset.sequence == data.sequence
    //   );
    //   if (targetElement) {
    //     targetElement.value = data.benefit;
    //   } else {
    //     console.error(`Target not found for sequence: ${data.sequence}`);
    //   }
    // });
  }

  toggleFields() {
    console.log("--- in toggle --- ")
    const selector = this.element.querySelector('[data-action*="change->general-form#toggleFields"]');
    if (selector) {
      const selectedValue = selector.value
      this.field_match = false;
      this.dependentFieldTargets.forEach((field) => {
        // Check a data attribute on the field to see if it matches the selected value
        if (field.dataset.parentValue === selectedValue) {
          if (selectedValue == "network_logo") {
            field.parentElement.parentElement.classList.remove("hidden");
          } else {
            field.parentElement.classList.remove("hidden");
          }
          this.field_match = true;
          console.log("- ", selectedValue)
          console.log("-- ", this.field_match)
        } else {
          if (field.dataset.parentValue == "network_logo") {
            field.parentElement.parentElement.classList.add("hidden");
          } else {
            field.parentElement.classList.add("hidden");
          }
        }
      });
      if (!this.field_match) {
          console.log("--- ", this.field_match)
          const defaultOption = this.dependentFieldTargets.find(target => {
            return target.dataset.parentValue === 'default';
          });
          defaultOption.parentElement.classList.remove("hidden");
        }
    }
  }
}