import { createApp } from "vue";
import SetReferrer from "ChillPersonAssets/vuejs/_components/AccompanyingPeriod/SetReferrer.vue";
import { fetchResults } from "ChillMainAssets/lib/api/apiMethods.ts";

/**
 *
 * To start this app, add this container into recordAction passed as argument to
 *  `ChillPerson/AccompanyingPeriod/_list_item.html.twig`:
 *
 *  ```html+twig
 *  {% if is_granted('CHILL_PERSON_ACCOMPANYING_PERIOD_UPDATE', period) %}
 *  <li>
 *  <span data-set-referrer-app="data-set-referrer-app" data-set-referrer-accompanying-period-id="{{ period.id }}"></span>
 *  </li>
 *  {% endif %}
 *  ```
 *
 *  The app will update the referrer displayed into dedicated span
 */

document.querySelectorAll("[data-set-referrer-app]").forEach(function (el) {
  const periodId = Number.parseInt(el.dataset.setReferrerAccompanyingPeriodId);
  const jobId = Number.parseInt(el.dataset.setReferrerJobId);
  const url = `/api/1.0/person/accompanying-course/${periodId}/referrers-suggested.json`;

  fetchResults(url).then((suggested) => {
    const filteredSuggested = suggested.filter((s) =>
      s.user_job ? s.user_job.id === jobId : false,
    );
    const app = createApp({
      components: {
        SetReferrer,
      },
      template:
        '<set-referrer :suggested="filteredSuggested" :periodId="periodId" @referrerSet="onReferrerSet"></set-referrer>',
      data() {
        return {
          periodId,
          filteredSuggested,
          original: filteredSuggested,
        };
      },
      methods: {
        onReferrerSet(ref) {
          const bloc = document.querySelector(
            `[data-accompanying-period-id="${this.periodId}"]`,
          );
          if (bloc === null) {
            console.error("bloc not found");
            return;
          }

          const label = bloc.querySelector("[data-referrer-text]");

          if (label === null) {
            console.error("label not found");
            return;
          }

          label.textContent = ref.text;
          label.classList.remove("chill-no-data-statement");

          this.filteredSuggested = this.original.filter(
            (user) => user.id !== ref.id,
          );
        },
      },
    });

    app.mount(el);
  });
});
