<template>
  <v-hover #default="{ isHovering, props }">
    <v-card
      id="drag-set"
      :class="[state !== FloatingState.REGULAR ? 'px-1 pb-1 pt-2' : 'px-4 py-2']"
      :max-width="state === FloatingState.VERTICAL_SQUASH ? 56 : state === FloatingState.HORIZONTAL_SQUASH ? 286 : 266"
      v-bind="props"
      class="position-relative d-flex"
      style="
        border-radius: 12px;
        text-align: left;
        z-index: 200;
        box-shadow:
          0px 2px 4px -2px rgba(29, 29, 73, 0.1),
          0px 4px 6px -1px rgba(29, 29, 73, 0.1) !important;
      "
      :style="{
        opacity: isHovering ? '1' : 0.9,
        'flex-direction': state === FloatingState.HORIZONTAL_SQUASH ? 'row' : 'column',
        ...style
      }"
    >
      <v-card-actions
        class="mb-0"
        :class="[state !== FloatingState.REGULAR ? 'px-0 py-0' : 'py-1']"
        style="min-height: 0px; gap: 0"
      >
        <v-spacer />
        <v-icon style="transform: rotate(90deg)" class="drag-handler shark-400" icon="drag_indicator" size="32" />
        <v-spacer />
      </v-card-actions>
      <v-divider
        :class="[state === FloatingState.HORIZONTAL_SQUASH ? 'mx-2' : 'my-2']"
        thickness="2"
        v-if="state !== FloatingState.REGULAR"
        :vertical="state === FloatingState.HORIZONTAL_SQUASH"
      />
      <v-tabs
        :class="[state]"
        fixed-tabs
        :mandatory="false"
        :model-value="activeIndex"
        hide-slider
        :show-arrows="false"
        :direction="state === FloatingState.VERTICAL_SQUASH ? 'vertical' : 'horizontal'"
      >
        <template v-for="tab in tabs">
          <v-tooltip location="bottom" open-delay="1000">
            <template #activator="{ props }">
              <v-tab v-bind="props" @click="tab.click">
                <v-icon :icon="tab.icon" size="lg" />
              </v-tab>
            </template>
            <span>{{ tab.tooltip }} {{ translateTooltipShortcut(tab.tooltipShortcut) }}</span>
          </v-tooltip>
        </template>
      </v-tabs>
    </v-card>
  </v-hover>
</template>

<script setup lang="ts">
import { computed, nextTick, onMounted, onUnmounted, watch } from 'vue';
import interact from 'interactjs';
import { storeToRefs } from 'pinia';
import { Interactable } from '@interactjs/core/Interactable';
import { FloatingState, useMcadFloatingStore } from '@/stores/mcad-floating.store';
import { useI18n } from 'vue-i18n';
import { SHORTCUT_TEXT, translateTooltipShortcut } from '@/functions/translateTooltipShortcut';
import { useToolStore } from '@/stores/tool.store';
import { useToolGroup } from '@/composables/useToolGroup';

let interactable: Interactable | null = null;

const { t } = useI18n();
const { x, y, style, state, isDragging } = storeToRefs(useMcadFloatingStore());
const { mcadMoveTool, mcadRotateTool, mcadScaleTool, mcadSelectTool } = useToolStore();
const { activeTool, activeIndex, toggleTool } = useToolGroup(mcadMoveTool, mcadRotateTool, mcadScaleTool);

const tabs = computed(() => [
  {
    icon: 'drag_pan',
    click: move,
    tooltip: t('labels.mcadMove'),
    tooltipShortcut: SHORTCUT_TEXT.m
  },
  {
    icon: '3d_rotation',
    click: rotate,
    tooltip: t('labels.mcadRotate'),
    tooltipShortcut: SHORTCUT_TEXT.r
  }
  // TODO: scale has not been implemented in 3CR
  // {
  //   icon: 'open_in_full',
  //   click: scale,
  //   tooltip: t('labels.mcadScale'),
  //   tooltipShortcut: SHORTCUT_TEXT.s
  // }
]);

watch([activeTool, mcadSelectTool.selected], ([activeTool, selected]) => {
  if (activeTool) {
    activeTool.selected.value = selected;
  }
});

onMounted(async () => {
  await nextTick();
  interactable = interact('#drag-set')
    .draggable({
      allowFrom: '.drag-handler',
      modifiers: [
        interact.modifiers.snap({
          targets: [interact.snappers.grid({ x: 1, y: 1 })],
          range: Infinity,
          relativePoints: [{ x: 0, y: 0 }]
        }),
        interact.modifiers.restrict({
          restriction: 'parent',
          elementRect: { top: 0, left: 0, bottom: 1, right: 1 },
          endOnly: true
        })
      ],
      inertia: true
    })
    .on('dragmove', function (event) {
      x.value += event.dx;
      y.value += event.dy;
      isDragging.value = true;
    })
    .on('mousedown', function (event) {
      isDragging.value = true;
      if (event.target.classList.contains('drag-handler')) {
        const hoverSelf = document.getElementById('hover-border');
        if (hoverSelf) {
          return;
        }

        const self = document.getElementById('drag-set');
        const parent = self?.parentElement;
        const element = document.createElement('div');
        element.id = 'hover-border';

        element.style.width = 'calc(100%)';
        element.style.height = 'calc(100%)';
        element.style.position = 'absolute';
        element.style.top = '0';
        element.style.left = '0';
        element.style.transition = 'all 800ms ease-in-out';
        element.style.boxShadow = '0 0 8px 1px inset rgb(var(--v-theme-minsk_500))';

        element.style.border = '2px dashed rgb(var(--v-theme-minsk_500))';
        element.style.borderRadius = '12px';

        parent?.appendChild(element);
      }
    })
    .on('mouseup', function (event) {
      const hoverSelf = document.getElementById('hover-border');
      if (hoverSelf) {
        hoverSelf.remove();
        return;
      }
      isDragging.value = false;
    })
    .on('dragend', function (event) {
      const hoverSelf = document.getElementById('hover-border');
      if (hoverSelf) {
        hoverSelf.remove();
        return;
      }
      isDragging.value = false;
    });
});

onUnmounted(() => {
  interactable?.unset();
});

function move(): void {
  mcadSelectTool.isActive.value = toggleTool(mcadMoveTool);
}

function rotate(): void {
  mcadSelectTool.isActive.value = toggleTool(mcadRotateTool);
}

// TODO: scale has not been implemented in 3CR
// function scale(): void {
//   mcadSelectTool.isActive.value = toggleTool(mcadScaleTool);
// }
</script>
