<script setup>
import { ref } from 'vue';
import { useI18n } from 'vue-i18n';
import { useRouter } from 'vue-router';
import { useQuasar } from 'quasar';

import CreateDepartmentChild from '../CreateDepartmentChild.vue';

import axios from 'axios';
import useNotify from 'src/composables/useNotify.js';

const quasar = useQuasar();
const { t } = useI18n();
const router = useRouter();
const { notify } = useNotify();

const treeRef = ref(null);
const showCreateNodeFormVal = ref(false);
const creationNodeSelectedId = ref(null);
const expanded = ref([]);

const nodes = ref([{ id: null, name: t('Departments'), sons: true, children: [{}] }]);

const fetchedChildrensSet = ref(new Set());

const onNodeExpanded = (nodeKeysArray) => {
    // Verificar si el nodo ya fue expandido
    if (!fetchedChildrensSet.value.has(nodeKeysArray.at(-1))) {
        fetchedChildrensSet.value.add(nodeKeysArray.at(-1));
        fetchNodeLeaves(nodeKeysArray.at(-1)); // Llamar a la función para obtener los nodos hijos
    }
};

const fetchNodeLeaves = async (nodeKey) => {
    try {
        const node = treeRef.value.getNodeByKey(nodeKey);
        if (!node || node.sons === 0) return;

        const params = { parentId: node.id };
        const response = await axios.get('/departments/getLeaves', { params });

        // Si hay datos en la respuesta y tiene hijos, agregarlos al nodo actual
        if (response.data) {
            node.children = response.data;
            node.children.forEach((node) => {
                if (node.sons) node.children = [{}];
            });
        }
    } catch (err) {
        console.error('Error fetching department leaves');
        throw new Error();
    }
};

const removeNode = (node) => {
    const { id, parentFk } = node;
    quasar
        .dialog({
            title: t('Are you sure you want to delete it?'),
            message: t('Delete department'),
            ok: {
                push: true,
                color: 'primary',
            },
            cancel: true,
        })
        .onOk(async () => {
            try {
                await axios.post(`/Departments/${id}/removeChild`, id);
                notify(t('department.departmentRemoved'), 'positive');
                await fetchNodeLeaves(parentFk);
            } catch (err) {
                console.log('Error removing department');
            }
        });
};

const showCreateNodeForm = (nodeId) => {
    showCreateNodeFormVal.value = true;
    creationNodeSelectedId.value = nodeId;
};

const onNodeCreated = async () => {
    await fetchNodeLeaves(creationNodeSelectedId.value);
};

const redirectToDepartmentSummary = (id) => {
    if (!id) return;
    router.push({ name: 'DepartmentSummary', params: { id } });
};
</script>

<template>
    <QCard class="full-width" style="max-width: 800px">
        <QTree
            ref="treeRef"
            :nodes="nodes"
            node-key="id"
            label-key="name"
            v-model:expanded="expanded"
            @update:expanded="onNodeExpanded($event)"
        >
            <template #default-header="{ node }">
                <div
                    class="row justify-between full-width q-pr-md cursor-pointer"
                    @click.stop="redirectToDepartmentSummary(node.id)"
                >
                    <span class="text-uppercase">
                        {{ node.name }}
                    </span>
                    <div class="row justify-between" style="max-width: max-content">
                        <QIcon
                            v-if="node.id"
                            name="delete"
                            color="primary"
                            size="sm"
                            class="q-pr-xs cursor-pointer"
                            @click.stop="removeNode(node)"
                        >
                            <QTooltip>
                                {{ t('Remove') }}
                            </QTooltip>
                        </QIcon>
                        <QIcon
                            name="add"
                            color="primary"
                            size="sm"
                            class="cursor-pointer"
                            @click.stop="showCreateNodeForm(node.id)"
                        >
                            <QTooltip>
                                {{ t('Create') }}
                            </QTooltip>
                        </QIcon>
                    </div>
                </div>
            </template>
        </QTree>
        <QDialog
            v-model="showCreateNodeFormVal"
            transition-show="scale"
            transition-hide="scale"
        >
            <CreateDepartmentChild
                :parent-id="creationNodeSelectedId"
                @on-data-saved="onNodeCreated()"
            />
        </QDialog>
    </QCard>
</template>

<i18n>
    es:
        Departments: Departamentos
        Remove: Quitar
        Create: Crear
        Are you sure you want to delete it?: ¿Seguro que quieres eliminarlo?
        Delete department: Eliminar departamento
</i18n>
