import { createApp } from "vue";
import AccompanyingPeriodWorkSelectorModal from "../../vuejs/_components/AccompanyingPeriodWorkSelector/AccompanyingPeriodWorkSelectorModal.vue";
import { AccompanyingPeriodWork } from "../../types";

document.addEventListener("DOMContentLoaded", () => {
  const elements = document.querySelectorAll<HTMLDivElement>(
    'div[data-pick-entities-type="acpw"]',
  );
  elements.forEach((el) => {
    const uniqid = el.dataset.inputUniqid;

    if (undefined === uniqid) {
      throw "Uniqid not found on this element";
    }

    const input = document.querySelector<HTMLInputElement>(
      `input[data-input-uniqid="${uniqid}"]`,
    );

    if (null === input) {
      throw "Element with uniqid not found: " + uniqid;
    }

    const accompanyingPeriodIdAsString = input.dataset.accompanyingPeriodId;

    if (undefined === accompanyingPeriodIdAsString) {
      throw "accompanying period id not found";
    }

    const accompanyingPeriodId = Number.parseInt(accompanyingPeriodIdAsString);

    const app = createApp({
      template:
        '<accompanying-period-work-selector-modal :accompanying-period-id="accompanyingPeriodId" @pickWork="pickWork"></accompanying-period-work-selector-modal>',
      components: { AccompanyingPeriodWorkSelectorModal },
      data() {
        return { accompanyingPeriodId };
      },
      methods: {
        pickWork: function (payload: { work: AccompanyingPeriodWork }) {
          console.log("payload", payload);
          input.value = payload.work.id?.toString() ?? "";
        },
      },
    });

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