<template>
  <FlexCol>
    <FlexRow align="center" :gap="20">
      <IconButton
        v-if="item.hasChildren !== false"
        icon="arrow-right" 
        :rotate="open ? 90 : 0"
        :innerStyle="{ transition: 'transform 0.3s ease-in-out' }"
        @click="toggleOpen"
      />
      <CheckBox
        :key="item.value"
        :name="item.value"
        :text="item.text" 
        :disabled="item.disable"
      />
    </FlexRow>
    <CollapseBox :open="open" :anim="false">
      <FlexCol :padding="[10,0,10,30]">
        <CheckBoxTreeListItemWrapper
          v-for="child in item.children"
          :key="child.value"
          :item="child"
        />
      </FlexCol>
    </CollapseBox>
  </FlexCol>
</template>

<script setup lang="ts">
import { inject, ref } from 'vue';
import type { CheckBoxTreeListItem } from './CheckBoxTreeList.vue';
import CollapseBox from '@/components/display/CollapseBox.vue';
import CheckBox from '@/components/form/CheckBox.vue';
import FlexCol from '@/components/layout/FlexCol.vue';
import FlexRow from '@/components/layout/FlexRow.vue';
import IconButton from '@/components/basic/IconButton.vue';
import CheckBoxTreeListItemWrapper from './CheckBoxTreeListItemWrapper.vue';

const props = defineProps<{
  item: CheckBoxTreeListItem,
}>();

const open = ref(false);
const loadData = inject('loadData') as (pid?: number) => Promise<CheckBoxTreeListItem[]>;

function toggleOpen() {
  open.value = !open.value;
  if (open.value && (!props.item.children || props.item.children.length === 0))
    loadData(props.item.value).then((children) => {
      props.item.children = children;
    });
}
</script>

<style lang="scss">
.nana-collapse-item-icon {
  transition: transform 0.3s ease-in-out;

  &.open {
    transform: rotate(180deg);
  }
}
</style>