<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]">
        <Loadmore 
          v-if="loading || loadError"
          :status="loading ? 'loading' : 'error'"
          :errorText="loadError"
          @retry="loadChildren"
        />
        <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';
import Loadmore from '@/components/display/loading/Loadmore.vue';

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

const open = ref(false);
const loading = ref(false);
const loadError = ref('');
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))
    loadChildren();
}
function loadChildren() {
  loading.value = true;
  loadData(props.item.value).then((children) => {
    props.item.children = children;
    loadError.value = '';
  }).catch((err) => {
    props.item.children = [];
    loadError.value = '' + err;
  }).finally(() => {
    loading.value = false;
  });
}
</script>

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

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