<template>
  <div class="h-full w-full flex justify-between items-center">
    <!-- Activity List -->
    <div
      class="h-full w-full bg-neutral-10 border border-neutral-300 rounded-xl ml-4 p-4 space-y-2"
    >
      <p class="h2 pl-2 border-b mb-3">Activity list</p>
      <div class="h-[calc(100%_-_56px)]">
        <Draggable
          :list="datadata"
          :group="{ name: 'activity', pull: 'clone' }"
          itemKey="name"
          animation="300"
          :fallbackTolerance="5"
          :forceFallback="true"
          :ghostClass="'ghostSelected'"
          :dragClass="'dragSelected'"
          :sort="false"
          @end="onEnd"
          class="h-full flex flex-wrap justify-start content-start gap-4 px-2 overflow-y-auto scrollbar"
        >
          <template #item="{ element, index }">
            <div
              :class="
                listSequence.includes(element)
                  ? 'border-primary text-primary'
                  : ''
              "
              class="flex items-center w-[166px] border rounded p-2 bg-neutral-10 cursor-pointer hover:bg-primary/20"
              @dblclick="moveActItem(index, element)"
              :title="element"
            >
              <span
                class="whitespace-nowrap break-keep text-ellipsis overflow-hidden"
                >{{ element }}</span
              >
            </div>
          </template>
        </Draggable>
      </div>
    </div>
    <!-- sequence -->
    <div
      class="w-full h-full relative bg-neutral-10 border border-neutral-300 rounded-xl ml-4 p-4 space-y-2 text-sm"
    >
      <p class="h2 border-b border-500 mb-3">Sequence</p>
      <!-- No Data -->
      <div
        v-if="listSequence && listSequence.length === 0"
        class="p-4 w-[calc(100%_-_32px)] h-5/6 flex justify-center items-center absolute"
      >
        <p class="text-neutral-500">
          Please drag and drop at least two activities here and sort.
        </p>
      </div>
      <!-- Have Data -->
      <div class="m-auto w-full h-[calc(100%_-_56px)]">
        <div
          class="w-full h-full overflow-y-auto overflow-x-auto scrollbar px-4 text-center"
        >
          <draggable
            class="h-full"
            :group="{ name: 'activity' }"
            :list="listSequence"
            itemKey="name"
            animation="300"
            :forceFallback="true"
            :dragClass="'dragSelected'"
            :fallbackTolerance="5"
            @start="onStart"
            @end="onEnd"
            :component-data="getComponentData()"
            :ghostClass="'!opacity-0'"
          >
            <template #item="{ element, index }">
              <div :title="element">
                <div class="flex justify-center items-center">
                  <div
                    class="w-full p-2 border rounded bg-neutral-10 cursor-pointer hover:bg-primary/20"
                    @dblclick="moveSeqItem(index, element)"
                  >
                    <span>{{ element }}</span>
                  </div>
                  <span
                    class="material-symbols-outlined pl-1 cursor-pointer duration-300 hover:text-danger"
                    @click.stop="moveSeqItem(index, element)"
                    >close</span
                  >
                </div>
                <span
                  v-show="
                    index !== listSequence.length - 1 &&
                    index !== lastItemIndex - 1
                  "
                  class="pi pi-chevron-down !text-lg inline-block py-2 pr-7"
                ></span>
              </div>
            </template>
          </draggable>
        </div>
      </div>
    </div>
  </div>
</template>
<script setup>
// The Lucia project.
// Copyright 2023-2026 DSP, inc.  All rights reserved.
// Authors:
//   chiayin.kuo@dsp.im (chiayin), 2023/1/31
//   cindy.chang@dsp.im (Cindy Chang), 2024/5/30
//   imacat.yang@dsp.im (imacat), 2023/9/23
/**
 * @module components/Discover/Conformance/ConformanceSidebar/ActSeqDrag
 *   Drag-and-drop activity sequence builder for
 *   conformance rule configuration.
 */

import { ref, computed, onBeforeUnmount } from "vue";
import { sortNumEngZhtw } from "@/module/sortNumEngZhtw.js";
import emitter from "@/utils/emitter";
import { cloneDeep } from "lodash-es";

const props = defineProps(["data", "listSeq", "isSubmit", "category"]);

const listSequence = ref([]);
const lastItemIndex = ref(null);
const isSelect = ref(true);

const datadata = computed(() => {
  // Sort the Activity List
  let newData;
  if (props.data !== null) {
    newData = cloneDeep(props.data);
    sortNumEngZhtw(newData);
  }
  return newData;
});

/**
 * double click Activity List
 * @param {number} index data item index
 * @param {object} element data item
 */
function moveActItem(index, element) {
  listSequence.value.push(element);
}

/**
 * double click Sequence List
 * @param {number} index data item index
 * @param {object} element data item
 */
function moveSeqItem(index, element) {
  listSequence.value.splice(index, 1);
}

/**
 * get listSequence
 */
function getComponentData() {
  emitter.emit("getListSequence", {
    category: props.category,
    task: listSequence.value,
  });
}

/**
 * Element dragging started
 */
function onStart(evt) {
  const lastChild = evt.to.lastChild.lastChild;
  lastChild.style.display = "none";
  // Hide the dragged element at its original position
  const originalElement = evt.item;
  originalElement.style.display = "none";
  // When dragging the last element, hide the arrow of the second-to-last element
  const listIndex = listSequence.value.length - 1;
  if (evt.oldIndex === listIndex) lastItemIndex.value = listIndex;
}

/**
 * Element dragging ended
 */
function onEnd(evt) {
  // Show the dragged element
  const originalElement = evt.item;
  originalElement.style.display = "";
  // Show the arrow after drag ends, except for the last element
  const lastChild = evt.item.lastChild;
  const listIndex = listSequence.value.length - 1;
  if (evt.oldIndex !== listIndex) {
    lastChild.style.display = "";
  }
  // Reset: hide the second-to-last element's arrow when dragging the last element
  lastItemIndex.value = null;
}

// created
const newlist = cloneDeep(props.listSeq);
listSequence.value = props.isSubmit ? newlist : [];
emitter.on("reset", (data) => {
  listSequence.value = [];
});

onBeforeUnmount(() => {
  emitter.off("reset");
});
</script>
<style scoped>
@reference "../../../../assets/tailwind.css";
.ghostSelected {
  @apply bg-primary/20;
}
.dragSelected {
  @apply !opacity-100;
}
</style>
