<script setup>
import { useRoute, useRouter } from 'vue-router';
import { computed, ref, watch } from 'vue';
import { useI18n } from 'vue-i18n';
import VnPaginate from 'components/ui/VnPaginate.vue';
import SubRoleCreateForm from './SubRoleCreateForm.vue';
import { useVnConfirm } from 'composables/useVnConfirm';
import { useArrayData } from 'composables/useArrayData';
import useNotify from 'src/composables/useNotify.js';
import axios from 'axios';

const { t } = useI18n();
const route = useRoute();
const router = useRouter();
const { openConfirmationModal } = useVnConfirm();
const { notify } = useNotify();
const paginateRef = ref(null);
const createSubRoleDialogRef = ref(null);
const arrayData = useArrayData('SubRoles');
const store = arrayData.store;

const data = computed(() => {
    const dataCopy = store.data;
    return dataCopy.sort((a, b) => a.inherits?.name.localeCompare(b.inherits?.name));
});

const filter = computed(() => ({
    where: { role: route.params.id },
    include: {
        relation: 'inherits',
        scope: {
            fields: ['id', 'name', 'description'],
        },
    },
}));

const urlPath = computed(() => `RoleInherits`);

const columns = computed(() => [
    {
        name: 'name',
    },
    {
        name: 'action',
    },
]);

const deleteSubRole = async (row) => {
    try {
        await axios.delete(`${urlPath.value}/${row.id}`);
        fetchSubRoles();
        notify(
            t('Role removed. Changes will take a while to fully propagate.'),
            'positive'
        );
    } catch (error) {
        console.error(error);
    }
};

const createSubRole = async (subRoleFormData) => {
    try {
        await axios.post(urlPath.value, subRoleFormData);
        notify(
            t('Role added! Changes will take a while to fully propagate.'),
            'positive'
        );
        fetchSubRoles();
    } catch (error) {
        console.error(error);
    }
};

watch(
    () => route.params.id,
    () => {
        store.url = urlPath.value;
        store.filter = filter.value;
        fetchSubRoles();
    }
);

const fetchSubRoles = () => paginateRef.value.fetch();

const openCreateSubRoleForm = () => createSubRoleDialogRef.value.show();

const redirectToRoleSummary = (id) =>
    router.push({ name: 'RoleSummary', params: { id } });
</script>

<template>
    <QPage class="column items-center q-pa-md">
        <div class="full-width" style="max-width: 400px">
            <VnPaginate
                ref="paginateRef"
                data-key="SubRoles"
                :filter="filter"
                :url="urlPath"
                auto-load
            >
                <template #body="{ rows }">
                    <QTable :rows="data" :columns="columns" hide-header>
                        <template #body="{ row, rowIndex }">
                            <QTr
                                @click="redirectToRoleSummary(row.inherits?.id)"
                                class="cursor-pointer"
                            >
                                <QTd>
                                    <div class="column">
                                        <span>{{ row.inherits?.name }}</span>
                                        <span class="color-vn-label">{{
                                            row.inherits?.description
                                        }}</span>
                                    </div>
                                </QTd>
                                <QTd style="width: 50px !important">
                                    <QIcon
                                        name="delete"
                                        size="sm"
                                        class="cursor-pointer"
                                        color="primary"
                                        @click.stop.prevent="
                                            openConfirmationModal(
                                                t('El rol va a ser eliminado'),
                                                t('¿Seguro que quieres continuar?'),
                                                () => deleteSubRole(row, rows, rowIndex)
                                            )
                                        "
                                    >
                                        <QTooltip>
                                            {{ t('globals.delete') }}
                                        </QTooltip>
                                    </QIcon>
                                </QTd>
                            </QTr>
                        </template>
                    </QTable>
                </template>
            </VnPaginate>
        </div>
        <QDialog ref="createSubRoleDialogRef">
            <SubRoleCreateForm @on-submit-create-subrole="createSubRole" />
        </QDialog>
        <QPageSticky position="bottom-right" :offset="[18, 18]">
            <QBtn
                fab
                icon="add"
                shortcut="+"
                color="primary"
                @click="openCreateSubRoleForm()"
            >
                <QTooltip>{{ t('warehouses.add') }}</QTooltip>
            </QBtn>
        </QPageSticky>
    </QPage>
</template>

<i18n>
es:
    Role removed. Changes will take a while to fully propagate.: Rol eliminado. Los cambios tardaran un tiempo en propagarse completamente.
    Role added! Changes will take a while to fully propagate.: ¡Rol añadido! Los cambios tardaran un tiempo en propagarse completamente.
    El rol va a ser eliminado: Role will be removed
    ¿Seguro que quieres continuar?: Are you sure you want to continue?
</i18n>
