<script setup lang="ts">
import { Icon } from '@iconify/vue';
import { computed } from 'vue';

type Node = {
  [key: string]: any;
  opened?: boolean;
  checked?: boolean;
  bg?: string;
  fg?: string;
  icon?: string;
  displayDropIcon?: boolean;
  children?: Node[];
};

type Props = {
  level?: number;
  keyTitle?: string;
  keySubtitle?: string;
  expandable?: boolean;
  hideCheckBox?: boolean;
  iconSize?: string;
  selectable?: boolean;
  selectedNode?: Node[];
  ancestorNode?: Node[];
  decoration?: {
    level?: number;
    bg?: string;
    fg?: string;
    icon?: string;
  }[];
};

const props = defineProps<Props>();
const nodes = defineModel<Node[]>('nodes', { required: true });

const emits = defineEmits<{
  (e: 'checked'): void;
  (e: 'select', node: Node, ancestor?: Node[]): void;
  (e: 'open', node: Node, ancestor?: Node[]): void;
}>();

const dec = props.decoration?.find((v) => v.level === (props.level || 0));
const maxLevel = computed(() =>
  props.decoration?.reduce((max, v) => {
    return v.level && v.level > max ? v.level : max;
  }, 0),
);

function recursiveDeselect(node: Node) {
  if (node.children) {
    node.children.forEach((v) => {
      v.checked = false;
      recursiveDeselect(v);
    });
  }
}
function toggleCheck(node: Node) {
  node.checked = !node.checked;
  if (node.checked === false) recursiveDeselect(node);
  if (node.checked === true) emits('checked');
}

function toggleExpand(node: Node, ancestor?: []) {
  node.opened = !node.opened;
  emits('open', node, ancestor);
}
</script>

<template>
  <div
    class="tree-container"
    :class="{
      'q-pl-xl': level && level > 0,
      'last-children': level && level === maxLevel,
    }"
  >
    <div v-for="(node, i) in nodes" class="tree-item" :key="i">
      <slot
        v-if="$slots['item']"
        name="item"
        :data="{ node, toggleExpand, toggleCheck }"
      />

      <template v-else>
        <div
          class="item__content row items-center no-wrap"
          :class="{ active: selectedNode?.includes(node) }"
          @click="
            () => (selectable ? $emit('select', node) : toggleExpand(node))
          "
        >
          <div style="width: var(--size-6); margin-right: var(--size-1)">
            <div
              v-if="level !== maxLevel"
              class="q-mr-md"
              :style="`color: ${
                !node.displayDropIcon &&
                (!node.children || node.children.length === 0)
                  ? 'transparent'
                  : $q.dark.isActive
                    ? 'var(--gray-7)'
                    : 'var(--gray-4)'
              }`"
            >
              <q-icon
                name="mdi-chevron-down-circle"
                size="sm"
                :style="`transform: rotate(${node.opened ? '180deg' : '0'}); transition: transform 0.3s ease;`"
                @click.stop="
                  !node.displayDropIcon &&
                  (!node.children || node.children.length === 0)
                    ? $emit('select', node)
                    : toggleExpand(node)
                "
              />
            </div>
          </div>

          <label
            v-if="!hideCheckBox"
            class="flex items-center item__checkbox"
            @click.stop
          >
            <input
              type="checkbox"
              v-model="node.checked"
              :style="`accent-color: var(--blue-7)`"
              @click="toggleCheck(node)"
            />
          </label>

          <div
            class="item__icon flex items-center justify-center"
            :style="`background: ${node.bg || dec?.bg}; color: ${node.fg || dec?.fg}; height: ${iconSize}; width: ${iconSize}`"
          >
            <div
              class="flex items-center justify-center"
              :style="`height: calc(${iconSize} - 40%); width: calc(${iconSize} - 40%)`"
            >
              <Icon
                v-if="(node.icon && dec && dec.icon) || (dec && dec.icon)"
                :icon="node.icon || dec.icon"
                class="full-width full-height"
              />
            </div>
          </div>

          <div class="column">
            <span class="item__title">
              {{ node[keyTitle || 'title'] || 'No Title' }}
            </span>
            <span class="item__subtitle">
              {{ node[keySubtitle || 'subtitle'] || 'No Subtitle' }}
            </span>
          </div>
        </div>
      </template>

      <transition name="slide">
        <div
          v-if="node.opened && node.children && node.children.length > 0"
          class="tree-children"
        >
          <TreeView
            :iconSize
            :hideCheckBox
            :selectable
            :selectedNode
            class="item__children"
            v-if="node.children"
            v-model:nodes="node.children"
            @open="
              (n) => {
                $emit(
                  'open',
                  n,
                  !props.ancestorNode || props.ancestorNode.length === 0
                    ? [node]
                    : [...props.ancestorNode, node],
                );
              }
            "
            @checked="
              () => {
                node.checked = true;
                $emit('checked');
              }
            "
            @select="
              (v) =>
                $emit(
                  'select',
                  v,
                  !props.ancestorNode || props.ancestorNode.length === 0
                    ? [node]
                    : [...props.ancestorNode, node],
                )
            "
            :level="(level || 0) + 1"
            :ancestorNode="
              !props.ancestorNode || props.ancestorNode.length === 0
                ? [node]
                : [...props.ancestorNode, node]
            "
            :expandable
            :decoration
          />
        </div>
      </transition>
    </div>
  </div>
</template>

<style lang="css">
.tree-container {
  display: flex;
  flex-direction: column;
  user-select: none;
  gap: var(--size-2);

  & .tree-item {
    & .item__content {
      border: solid 1px transparent;
      border-radius: var(--radius-2);
      padding: 0.1rem 0.5rem;

      &:hover {
        background: hsla(0 0% 0% / 0.1);
      }
    }

    & .item__checkbox {
      padding: 0.1rem 0.5rem;
      margin-right: 1rem;
    }

    & .item__icon {
      margin-right: 1rem;
      width: 1.5rem;
      height: 1.5rem;
      border-radius: 50%;
    }

    & .item__title {
      font-weight: 600;
    }

    & .item__subtitle {
      font-size: 80%;
      color: hsla(var(--text-mute-2));
    }

    & .tree-children {
      padding-top: var(--size-2);
    }

    & .active {
      border-radius: var(--radius-2);
      border: solid 1px hsl(var(--info-bg));
      background: hsla(var(--info-bg) / 0.1);
    }
  }
}

.slide-enter-active {
  transition: all 0.1s ease-out;
}

.slide-leave-active {
  transition: all 0.1s cubic-bezier(1, 0.5, 0.8, 1);
}

.slide-enter-from,
.slide-leave-to {
  transform: translateY(-20px);
  opacity: 0;
}
</style>
