import { useCallback, useEffect, useRef } from 'react';
import { TableConfig, useTableManager } from '@/hooks/use-table-manager';
import {
    ITripDriverAssignmentDetails,
    ITripDriverAssignmentList,
    TripDriverAssignmentSearchParams,
} from '@/shared/types/circuit';
import { useTripDriverAssignmentStore } from '@/shared/api/stores/circuit-service/tripDriverAssignmentStore';
import { DEFAULT_TRIP_DRIVER_ASSIGNMENT_TABLE_HEAD } from '@/shared/_mock/_chauffeurs';
import { enqueueSnackbar } from 'notistack';

export function useTripDriverAssignmentTable(circuitId: string) {
    const abortControllerRef = useRef<AbortController | null>(null);
    const { assignments, totalElements, loading, error, searchAssignments, getAssignmentDetails, loadingDetails } =
        useTripDriverAssignmentStore();

    const assignmentConfig: TableConfig<ITripDriverAssignmentList> = {
        initialData: assignments || [],
        defaultTableHead: DEFAULT_TRIP_DRIVER_ASSIGNMENT_TABLE_HEAD,
    };

    const tableManager = useTableManager<ITripDriverAssignmentList>(assignmentConfig);

    const getFilterParams = () => {
        const filterParams: Record<string, string | number | boolean> = {};
        Object.entries(tableManager.filters).forEach(([key, { value }]) => {
            if (value !== undefined && value !== null && value !== '') {
                filterParams[key] = value;
            }
        });
        return filterParams;
    };

    useEffect(() => {
        const baseParams: TripDriverAssignmentSearchParams = {
            circuitId,
            page: tableManager.table.page || 0,
            size: tableManager.table.rowsPerPage || 20,
            sortBy: tableManager.table.orderBy || 'id',
            sortDirection: tableManager.table.order?.toUpperCase() as 'ASC' | 'DESC',
        };

        const filterParams = getFilterParams();

        const newParams = {
            ...baseParams,
            page: Object.keys(filterParams).length > 0 ? 0 : baseParams.page,
            ...filterParams,
        };

        const controller = new AbortController();
        abortControllerRef.current = controller;

        const fetchData = async () => {
            try {
                await searchAssignments(newParams, controller.signal);
            } catch (error: any) {
                if (!controller.signal.aborted) {
                    enqueueSnackbar(error.message || 'Erreur de chargement', {
                        variant: 'error',
                    });
                }
            }
        };

        const hasFilters = Object.keys(filterParams).length > 0;
        const debounceTime = hasFilters ? 300 : 0;
        
        const timer = setTimeout(fetchData, debounceTime);

        return () => {
            controller.abort();
            clearTimeout(timer);
        };
        // eslint-disable-next-line react-hooks/exhaustive-deps
    }, [
        circuitId,
        tableManager.table.page,
        tableManager.table.rowsPerPage,
        tableManager.table.orderBy,
        tableManager.table.order,
        tableManager.filters,
    ]);

    const getAndViewAssignment = useCallback(
        async (assignmentId: string, handleView: (details: ITripDriverAssignmentDetails) => void) => {
            try {
                const assignmentDetails = await getAssignmentDetails(assignmentId);
                handleView(assignmentDetails);
            } catch (error: any) {
                enqueueSnackbar(error.message || 'Erreur lors de la récupération du détail', {
                    variant: 'error',
                });
            }
        },
        [getAssignmentDetails]
    );

    return {
        ...tableManager,
        loading,
        error,
        totalAssignments: totalElements,
        filteredData: assignments,
        getAndViewAssignment,
        loadingDetails,
        };
}
