<template>
    <div class="overflow-y-auto h-full">
        <Toolbar :config="toolbarConfig" class="mb-6" />

        <div v-if="activityStore.loading" class="flex justify-center py-8">
            <div class="animate-spin rounded-full h-10 w-10 border-t-2 border-b-2 border-indigo-500"></div>
        </div>

        <div v-else-if="activityStore.error" class="bg-red-100 dark:bg-red-900/20 border-l-4 border-red-500 text-red-700 dark:text-red-400 p-4 mb-6">
            <p>{{ activityStore.error }}</p>
        </div>

        <div v-else class="container mx-auto p-2">
            <div class="bg-white dark:bg-gray-800 overflow-hidden shadow rounded-lg">
                <div class="overflow-x-auto">
                    <table class="min-w-full bg-white dark:bg-gray-800">
                        <thead>
                            <tr class="bg-gray-200 dark:bg-gray-700 text-gray-800 dark:text-gray-200">
                                <th class="w-1/12 py-3 px-4 text-left">
                                    <input
                                        type="checkbox"
                                        class="form-checkbox h-5 w-5 text-green-600"
                                        @change="toggleSelectAll" />
                                </th>
                                <th class="w-2/12 py-3 px-4 text-left">Type</th>
                                <th class="w-2/12 py-3 px-4 text-left">Statut</th>
                                <th class="w-3/12 py-3 px-4 text-left">Informations</th>
                                <th class="w-3/12 py-3 px-4 text-left">Progression</th>
                                <th class="w-1/12 py-3 px-4 text-left">Actions</th>
                            </tr>
                        </thead>
                        <tbody class="text-gray-700 dark:text-gray-300">
                            <template v-if="activityStore.jobs.length === 0">
                                <tr>
                                    <td colspan="6" class="py-8 px-4 text-center text-gray-500">
                                        <div class="flex flex-col items-center">
                                            <ClockIcon class="h-12 w-12 text-gray-300 dark:text-gray-600 mb-4" />
                                            <p class="text-lg font-medium dark:text-gray-300">Aucune activité trouvée</p>
                                            <p class="text-sm dark:text-gray-400">Aucune activité ne correspond aux filtres actuels.</p>
                                        </div>
                                    </td>
                                </tr>
                            </template>
                            <template v-else>
                                <JobItem
                                    v-for="job in activityStore.jobs"
                                    :key="job.id"
                                    :job="job"
                                    @delete="deleteJob" />
                            </template>
                        </tbody>
                    </table>
                </div>

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

<script setup>
    import { ArrowPathIcon, ClockIcon, FunnelIcon, TrashIcon } from '@heroicons/vue/24/outline';
import { computed, onMounted, ref } 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 selectedAll = ref(false);

    // Statuts disponibles pour le filtre
    const statusOptions = [
        { value: ['pending', 'in_progress'], label: 'Actifs' },
        { value: ['pending', 'in_progress', 'completed', 'failed'], label: 'Tous' },
        { value: ['completed'], label: 'Terminés' },
        { value: ['failed'], label: 'En erreur' },
        { value: ['pending'], label: 'En attente' },
        { value: ['in_progress'], label: 'En cours' }
    ];

    // Index du statut actif (par défaut "Actifs")
    const activeStatusIndex = ref(0);

    // Configuration de la toolbar réactive
    const toolbarConfig = computed(() => ({
        leftSection: [
            {
                icon: FunnelIcon,
                type: 'dropdown',
                label: statusOptions[activeStatusIndex.value].label,
                active: false,
                items: statusOptions.map((option, index) => ({
                    label: option.label,
                    isSelected: index === activeStatusIndex.value,
                    onClick: () => setStatusFilter(index)
                }))
            }
        ],
        rightSection: [
            {
                icon: ArrowPathIcon,
                type: 'button',
                label: 'Rafraîchir',
                onClick: refreshJobs
            },
            {
                icon: TrashIcon,
                type: 'button',
                label: 'Supprimer visibles',
                onClick: deleteVisibleJobs
            }
        ]
    }));

    onMounted(() => {
        loadJobs();
    });

    function loadJobs() {
        activityStore.loadJobs();
    }

    function refreshJobs() {
        loadJobs();
    }

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

    function toggleSelectAll() {
        selectedAll.value = !selectedAll.value;
        // La logique pour sélectionner tous les jobs serait ajoutée ici
    }

    function setStatusFilter(index) {
        if (index >= 0 && index < statusOptions.length) {
            activeStatusIndex.value = index;
            activityStore.updateFilter({ status: statusOptions[index].value });
        }
    }

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

    function deleteVisibleJobs() {
        if (activityStore.jobs.length === 0) {
            return;
        }

        const statusLabel = statusOptions[activeStatusIndex.value].label.toLowerCase();
        if (confirm(`Voulez-vous vraiment supprimer tous les jobs ${statusLabel} ?`)) {
            activityStore.deleteJobs({ status: activityStore.filter.status });
        }
    }
</script>
