import { Controller } from "@hotwired/stimulus"

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

  connect() {
    console.log("--- in toggle connect --- ")
    const selector = this.selectFieldTarget;
    if (selector.value) {
      const selectedValue = selector.value
      this.dependentFieldTargets.forEach((field) => {
        if (field.value) {
          if (selectedValue == "network_logo") {
            field.parentElement.parentElement.parentElement.classList.remove("hidden");
          } else {
            field.parentElement.classList.remove("hidden");
          }
        }
      })
    }
  }

  toggleFields() {
    console.log("--- in toggle --- ")
    const selector = this.selectFieldTarget;
    if (selector.value) {
      const selectedValue = selector.value
      this.field_match = false;
      this.dependentFieldTargets.forEach((field) => {
        // console.log("- ", selectedValue)
        // console.log("-- ", this.field_match)
        // 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.parentElement.classList.remove("hidden");
          } else {
            field.parentElement.classList.remove("hidden");
          }
          this.field_match = true;
        } else {
          if (field.dataset.parentValue == "network_logo") {
            field.parentElement.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");
        }
    }
  }
}