import { useCallback, useEffect } from 'react';
import { TableConfig, useTableManager } from '@/hooks/use-table-manager';
import { TableType } from '@/shared/types/common';
import { TripCircuitDetails, TripCircuitDTO, } from '@/shared/types/circuit';
import { enqueueSnackbar } from 'notistack';
import { DEFAULT_CUSTOMIZED_TRIPS_TABLE_HEAD } from '@/shared/_mock/_circuitTrajets';
import { useTripCircuitStore } from '@/shared/api/stores/circuit-service/tripCircuitStore';
import { deduplicateTrips } from '@/shared/sections/trajet/utils/trip-deduplication';

export function useCustomizedTripsTable(circuitId: string) {
    const { getTripCircuitById, loadingDetailsCustomized, getPersonalizedTrips, personalizedTrips, loadingPersonalizedTrips } = useTripCircuitStore();

    const trajetConfig: TableConfig<TripCircuitDTO> = {
        type: TableType.Trajet,
        initialData: personalizedTrips || [],
        defaultTableHead: DEFAULT_CUSTOMIZED_TRIPS_TABLE_HEAD,
    };

    const tableManager = useTableManager<TripCircuitDTO>(trajetConfig);

    useEffect(() => {

        const fetch = async () => {
            try {
                await getPersonalizedTrips(circuitId);
            } catch (error: any) {
                enqueueSnackbar(error.message || 'Erreur lors de la recherche des trajets', { variant: 'error' });
            }
        };
        fetch();
    }, [getPersonalizedTrips, circuitId]);

    const getTripCircuit = useCallback(
        async (id: string, handleView: (details: TripCircuitDetails) => void) => {
            try {
                const details = await getTripCircuitById(id, 'customized');
                if (details) {
                    handleView(details);
                }
            } catch (error: any) {
                enqueueSnackbar(error.message || 'Erreur lors de la récupération du détail', { variant: 'error' });
            }
        },
        [getTripCircuitById]
    );

    return {
        ...tableManager,
        filteredData: deduplicateTrips(tableManager.filteredData),
        loading: loadingPersonalizedTrips,
        getTripCircuit,
        loadingDetails: loadingDetailsCustomized,
    };
}