<template>
    <transition-component
        group
        enter-class="animate__animated animate__fadeInUp animate__delay-1 animate__faster p-r-30"
        leave-class="animate__animated animate__fadeOutDown animate__faster p-r-30"
        style="min-height: 300px;width:100%"
    >
        <loading-component
            v-show="isLoading"
            key="1"
            style="height: 200px; top: 0;"
            color="success"
        />
        <div v-show="!isLoading" key="2" class="row">
            <div class="col">
                <div class="row">
                    <div class="col">
                        <div
                            v-show="!listData.length && !isLoading && emptyListSection"
                            class="row align-items-center justify-content-center p-t-50 p-b-50"
                        >
                            <div class="col-10">
                                <div class="row align-items-center justify-content-center hint-text">
                                    <div class="col-4 hint-text">
                                        <img :src="asset('images/not-found-illustration.png')" class="w-100 hint-text">
                                    </div>
                                </div>
                                <div class="row text-center">
                                    <div class="col">
                                        <div class="row m-t-20">
                                            <div class="col">
                                                <p class="all-caps no-margin fs-11" style="letter-spacing: 2px;">Nothing To Show Here</p>
                                            </div>
                                        </div>
                                        <div class="row m-t-5 align-items-center justify-content-center">
                                            <div class="col">
                                                <small class="fs-9 muted all-caps font-lato" style="letter-spacing: 2px">
                                                    There is no results found, Try adjusting your filters to find what you are looking for.
                                                </small>
                                            </div>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div class="row">
                            <div class="col">
                                <div class="list disable-text-selection" data-check-all="checkAll">
                                    <div
                                        v-for="item in listData"
                                        :key="item.id"
                                        ref="list"
                                        class="row"
                                        :data="item"
                                    >
                                        <div class="col">
                                            <slot name="list" :data="item" />
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div class="row">
                            <div class="col">
                                <pagination-component ref="paginationRef" :section="section" class="mb-5" />
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </transition-component>
</template>

<script setup lang="ts">
import { computed, onMounted, ref, watch } from 'vue';
import { useQueueStore } from '@/stores/queue';
import { useUiStore } from '@/stores/ui';
import { useRequest } from '@/composables/useRequest';
import PaginationComponent from '@/components/general/elements/PaginationComponent.vue';

interface PaginationMeta {
    current_page: number;
    last_page: number;
}

// interface PaginationExpose {
//     makePagination: (newPagination: PaginationMeta) => void;
// }

const props = withDefaults(defineProps<{
    section: string;
    endpoint: string;
    options?: Record<string, unknown>;
    emptyListSection?: boolean;
}>(), {
    options: () => ({}),
    emptyListSection: true
});

const queueStore = useQueueStore();
const uiStore = useUiStore();
const { submit } = useRequest();

// const paginationRef = ref<PaginationExpose | null>(null);
const paginationRef = ref<InstanceType<typeof PaginationComponent> | null>(null);
const filters = ref<Record<string, unknown>>({ ...(props.options ?? {}) });

const isLoading = computed(() => uiStore.isLoading(props.section));
const listData = computed(() => queueStore.getListData(props.section));
const pendingList = computed(() => queueStore.isInCompleteQueue(props.section));

const asset = (path: string) => (window as any).Vapor.asset(path);

const setDecoratorDefault = () => {
    filters.value = queueStore.normalizeListFilters(filters.value);
};

const successHandler = (response: any) => {
    queueStore.setListComplete({
        name: props.section,
        data: response.payload?.data ?? []
    });
    paginationRef.value?.makePagination(response.payload?.meta ?? {});
};

const fetchList = async () => {
    const listDecorators = queueStore.getListDetails(props.section);
    if (!listDecorators) {
        return;
    }

    await submit(
        `${props.endpoint}?page=${listDecorators.page ?? 1}&filters=${JSON.stringify(listDecorators.filters ?? {})}`,
        'get',
        props.section,
        false,
        false,
        undefined,
        { successHandler }
    );
};

const updateFilters = async (nextFilters: Record<string, unknown>) => {
    filters.value = nextFilters;
    setDecoratorDefault();

    await submit(
        `${props.endpoint}?page=1&filters=${JSON.stringify(filters.value)}`,
        'get',
        props.section,
        false,
        false,
        undefined,
        { successHandler }
    );
};

watch(
    pendingList,
    (inComplete) => {
        if (inComplete) {
            fetchList();
        }
    },
    { immediate: true }
);

onMounted(() => {
    setDecoratorDefault();
    queueStore.updateListQueue({ name: props.section, page: 1, filters: { ...filters.value } });
});

defineExpose({
    // fetchList, //cief todo: 137 - we might not need this
    updateFilters
});
</script>
