<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 style="height: 200px; top: 0;" key="1" color="success" v-show="isLoading"></loading-component>
        <div class="row" key="2" v-show="!uiStore.isLoading(section)">
            <div class="col">
                <div class="row">
                    <div class="col">
                        <div class="row align-items-center justify-content-center p-t-50 p-b-50"  v-show="!queueStore.getListData(section).length && !isLoading && emptyListSection">
                            <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" v-show="!isLoading">
                            <div class="col">
                                <div class="list disable-text-selection" data-check-all="checkAll">
                                    <div class="row" ref="list" v-for="item in queueStore.getListData(section)" v-bind:key="item.id" :data="item">
                                        <div class="col">
                                            <slot name="list" :data="item"></slot>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                        <div class="row" v-show="!isLoading">
                            <div class="col">
                                <pagination-component :section="section" class="mb-5" ref="paginationRef"></pagination-component>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </transition-component>
</template>

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

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

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

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

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

const pendingList = computed(() => {
    return queueStore.isInCompleteQueue(props.section);
});

const getJob = computed(() => {
    return jobPollingStore.getJob(props.section);
});

const currentJob = () => {
    const job = getJob.value;
    if (!job) {
        throw new Error(`Polling job not found for ${props.section}`);
    }

    return job;
};

const getJobAttemptCount = computed(() => {
    return jobPollingStore.getJobAttemptCount(props.section);
});

const fetchList = () => {
    const listDecorators = queueStore.getListDetails(props.section);
    const url = props.endpoint + '?page=' + listDecorators.page + '&filters=' + JSON.stringify(listDecorators.filters);
    isLoading.value = true;
    jobPollingStore.submitJobRequest({ url, name: props.section });
};

const successHandler = (response: any) => {
    const result = JSON.parse(response.payload.data.result);
    result.meta = {
        current_page: result.meta.current_page,
        first_page_url: result.meta.first_page_url,
        from: result.meta.from,
        last_page: result.meta.last_page,
        last_page_url: result.meta.last_page_url,
        next_page_url: result.meta.next_page_url,
        path: result.meta.path,
        per_page: result.meta.per_page,
        prev_page_url: result.meta.prev_page_url,
        to: result.meta.to,
        total: result.meta.total
    };
    queueStore.setListComplete({ name: props.section, data: result.data });
    jobPollingStore.stopPollingJobResultByJobId(currentJob().jobId);
    if (paginationRef.value) {
        // paginationRef.value.makePagination(result.meta, result.links);
        paginationRef.value.makePagination(result.meta);
    }
    isLoading.value = false;
};

const errorHandler = () => {
    jobPollingStore.updatePollingJobResultByJobId({
        jobId: currentJob().jobId,
        isPolling: false,
        isFetchingResult: false
    });
};

const fetchJobResult = (isLastAttempt = false) => {
    jobPollingStore.updatePollingJobResultByJobId({
        jobId: currentJob().jobId,
        isPolling: false,
        isFetchingResult: true
    });
    try {
        let anotherEndpoint = route('api.job.fetch', currentJob().jobId);
        if (isLastAttempt) {
            anotherEndpoint = route('api.job.fetch.last.attempt', currentJob().jobId, isLastAttempt);
        }
        submit(anotherEndpoint, 'get', props.section, false, false, undefined, {
            successHandler,
            errorHandler
        });
    } catch (error) {
        console.error('Error fetchJobResult', error);
    }
};

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

watch(getJobAttemptCount, () => {
    if (getJob.value) {
        fetchJobResult(getJob.value.isLastAttempt);
    }
});

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