"use strict";

import {Controller} from "@hotwired/stimulus";
import Sortable from "sortablejs";
// @ts-ignore
import {getComponent} from "@symfony/ux-live-component";

export default class extends Controller {
  static values = {
    count: Number,
  };

  static targets = [
    "confirmedColumn",
    "waitlistedColumn",
    "waitingColumn",
    "withdrawnColumn",
    "rejectedColumn",
    "unfulfilledColumn",
  ];

  initialize() {
    getComponent(this.element).then((component) => {
      this.component = component;
      this.setupSortable();
      this.component.on("render:finished", () => {
        this.setupSortable();
      });
    });
  }

  connect() {
    this.setupSortable();
  }

  setupSortable() {
    const component = this.component;
    if (typeof component === "undefined") {
      return;
    }

    this.constructor.targets.forEach((targetName) => {
      const hasTarget =
        this[
          `has${targetName.charAt(0).toUpperCase() + targetName.slice(1)}Target`
        ];
      if (!hasTarget) {
        return;
      }

      const column = this[`${targetName}Target`];
      if (!(column instanceof HTMLElement)) {
        return;
      }

      const list = column.querySelector("ul[data-attendance-status]");
      if (!(list instanceof HTMLElement)) {
        return;
      }

      if (Sortable.get(list)) {
        Sortable.get(list).destroy();
      }

      Sortable.create(list, {
        group: "assign",
        ghostClass: "bg-yellow-50",
        filter: "a, button, el-menu",
        preventOnFilter: false,
        onChoose: function (event) {
          component.emit("selectParticipant", {
            participant: event.item.dataset.participantId,
          });
        },
        onAdd: (event) =>
          component.emit("statusChanged", {
            attendance: event.item.dataset.attendanceId, // event.items for multi-drag plugin (empty array for one item)
            newStatus: event.to.dataset.attendanceStatus,
            newIndex: event.newIndex,
          }),
        onUpdate: (event) =>
          component.emit("indexUpdated", {
            attendance: event.item.dataset.attendanceId,
            newIndex: event.newIndex,
          }),
        onSort: () =>
          (this.countValue = column.querySelectorAll("ul > li").length),
      });
    });
  }


  deselect(event) {
    if (!this.component || event.target.closest("li[data-participant-id]")) {
      return;
    }

    this.component.emit("unselectParticipant");
  }

  showContextMenu(event) {
    const row = event.currentTarget;
    const menu = row.querySelector("el-menu");
    if (!menu) return;

    event.preventDefault();

    const oldAnchor = menu.getAttribute("anchor");
    menu.removeAttribute("anchor");

    menu.style.position = "fixed";
    menu.style.left = `${event.clientX}px`;
    menu.style.top = `${event.clientY}px`;
    menu.style.margin = "0";

    if (menu.showPopover) {
      menu.showPopover();
    } else {
      menu.classList.remove("hidden");
    }

    const onToggle = (e) => {
      if (e.newState === "closed") {
        if (oldAnchor) {
          menu.setAttribute("anchor", oldAnchor);
        }
        menu.removeEventListener("toggle", onToggle);
      }
    };
    menu.addEventListener("toggle", onToggle);
  }
}
