<template>
    <div class="flex flex-col h-full">
        <Toolbar :config="toolbarConfig" />

        <div class="overflow-y-auto flex-1">
            <!-- Loading -->
            <div v-if="loading" class="flex justify-center py-12">
                <div class="animate-spin h-10 w-10 border-b-2 border-indigo-500 rounded-full"></div>
            </div>

            <!-- Error -->
            <div v-else-if="activityStore.error" class="px-6 py-8">
                <div class="bg-red-50 dark:bg-red-900 border border-red-200 dark:border-red-700 p-4">
                    <p class="text-red-800 dark:text-red-200">{{ activityStore.error }}</p>
                </div>
            </div>

            <!-- Content -->
            <section v-else class="border-t border-gray-200 dark:border-gray-700">
                <!-- Empty -->
                <div v-if="activityStore.jobs.length === 0" class="flex flex-col items-center justify-center py-20 text-gray-400 dark:text-gray-500">
                    <ClockIcon class="w-12 h-12 mb-3" />
                    <p class="text-base">Aucun job en cours ou en attente.</p>
                </div>

                <!-- Table -->
                <div v-else class="overflow-x-auto">
                    <table class="min-w-full">
                        <thead>
                            <tr class="border-b border-gray-200 dark:border-gray-700 text-xs font-semibold text-gray-400 dark:text-gray-500 uppercase tracking-wider">
                                <th class="w-2/11 py-3 px-6 text-left">Type</th>
                                <th class="w-2/11 py-3 px-4 text-left">Statut</th>
                                <th class="w-3/11 py-3 px-4 text-left">Informations</th>
                                <th class="w-3/11 py-3 px-4 text-left">Progression</th>
                                <th class="w-1/11 py-3 px-4 text-left">Actions</th>
                            </tr>
                        </thead>
                        <tbody class="divide-y divide-gray-100 dark:divide-gray-700/50 text-gray-700 dark:text-gray-300">
                            <JobItem
                                v-for="job in activityStore.jobs"
                                :key="job.id"
                                :job="job"
                                @delete="deleteJob" />
                        </tbody>
                    </table>
                </div>

                <!-- Pagination -->
                <Pagination
                    v-if="total > activityStore.limit"
                    :current-page="activityStore.currentPage"
                    :total-pages="activityStore.totalPages"
                    :total="total"
                    :limit="activityStore.limit"
                    :has-next-page="activityStore.hasNextPage"
                    :has-previous-page="activityStore.hasPreviousPage"
                    @page-change="changePage" />
            </section>
        </div>
    </div>
</template>

<script setup>
import { ArrowPathIcon, BarsArrowDownIcon, ClockIcon, TrashIcon } from '@heroicons/vue/24/outline';
import { storeToRefs } from 'pinia';
import { computed, onMounted, onUnmounted } from 'vue';
import Pagination from '../../../../shared/components/ui/Pagination.vue';
import Toolbar from '../../../../shared/components/ui/Toolbar.vue';
import { useActivityStore } from '../../application/store/activityStore';
import JobItem from '../components/JobItem.vue';

const activityStore = useActivityStore();

const { sortBy, sortOrder, total, loading } = storeToRefs(activityStore);

const isSortSelected = (by, order) => sortBy.value === by && sortOrder.value === order;

const toolbarConfig = computed(() => ({
    leftSection: [
        { type: 'label', text: 'Activité', class: 'text-sm font-medium' },
        { type: 'label', text: `(${total.value})`, class: 'text-sm text-gray-400' },
    ],
    rightSection: [
        {
            type: 'dropdown',
            icon: BarsArrowDownIcon,
            label: 'Trier',
            items: [
                {
                    label: 'Plus récent',
                    isSelected: isSortSelected('createdAt', 'DESC'),
                    onClick: () => activityStore.updateSort('createdAt', 'DESC'),
                },
                {
                    label: 'Plus ancien',
                    isSelected: isSortSelected('createdAt', 'ASC'),
                    onClick: () => activityStore.updateSort('createdAt', 'ASC'),
                },
                {
                    label: 'Par type',
                    isSelected: isSortSelected('type', 'ASC'),
                    onClick: () => activityStore.updateSort('type', 'ASC'),
                },
                {
                    label: 'Par statut',
                    isSelected: isSortSelected('status', 'ASC'),
                    onClick: () => activityStore.updateSort('status', 'ASC'),
                },
            ],
        },
        {
            type: 'button',
            icon: ArrowPathIcon,
            label: 'Rafraîchir',
            disabled: loading.value,
            onClick: () => activityStore.loadJobs(),
        },
        {
            type: 'button',
            icon: TrashIcon,
            label: 'Supprimer visibles',
            disabled: loading.value || total.value === 0,
            onClick: deleteVisibleJobs,
        },
    ],
}));

onMounted(() => {
    activityStore.loadJobs();
    activityStore.subscribeMercure();
});

onUnmounted(() => {
    activityStore.unsubscribeMercure();
});

function changePage(page) {
    activityStore.goToPage(page);
}

function deleteJob(id) {
    if (confirm('Voulez-vous vraiment supprimer ce job ?')) {
        activityStore.deleteJob(id);
    }
}

function deleteVisibleJobs() {
    if (activityStore.jobs.length === 0) return;
    if (confirm('Voulez-vous vraiment supprimer tous les jobs visibles ?')) {
        activityStore.deleteJobs({ status: ['pending', 'in_progress'] });
    }
}
</script>
