import { Controller } from "@hotwired/stimulus";

export default class extends Controller {
  static values = { url: String };
  static targets = ["benefit", "title"];

  connect() {
  }

  async fetchData(event) {
    const templateId = event.target.value;
    if (!templateId) {
      this.clearFields();
      return;
    }
    
    const url = `/id_card/plans/${templateId}/get_plan_template`
    const response = await fetch(url);
    const templatePlanData = await response.json();

    this.#updateFields(templatePlanData)
  }

  clearFields() {
  }

  async #updateFields(templatePlanData) {
    const titleElement = this.titleTarget
    if (!titleElement.value) {
      titleElement.value = templatePlanData.title.match(/^(.*\d)k(?=\d)/i)[0].replace(/(\d)/, ' $1')
    }
    const benefitTargetsList = this.benefitTargets
    templatePlanData.plan_benefits.forEach(function(bene) {
      const targetElement = benefitTargetsList.find(
        (element) => element.dataset.sequence == bene.sequence
      );
      if (targetElement) {
        targetElement.value = bene.benefit;
      } else {
        console.error(`Target not found for sequence: ${bene.sequence}`);
      }
    });
  }
}

// this[propertyName]
// const propertyName = `${valueName}Value`;
