import { TableConfig, useTableManager } from '@/hooks/use-table-manager';
import { TableType } from '@/shared/types/common';
import { DEFAULT_USAGER_TABLE_HEAD } from '@/shared/_mock/_usagers';
import { usePassengerStore } from '@/shared/api/stores/passengerStore';
import { useEffect, useRef } from 'react';
import { _PassengerStatus, IPassengerList, SearchPassengerParams } from '@/shared/types/passenger';
import { isValidFilterValue } from '@/utils/helper';
import { enqueueSnackbar } from 'notistack';
import { getValue } from '@/shared/_mock';
import { _RELATION_TYPE_OPTIONS } from '../utils/form-fields-usager';

export function useUsagerTable() {
    const abortControllerRef = useRef<AbortController | null>(null);
    const {
        passengers,
        totalElements,
        loading,
        error,
        searchPassengers,
        exportPassengers
    } = usePassengerStore();

    const passengerConfig: TableConfig<IPassengerList> = {
        type: TableType.Usager,
        initialData: passengers || [],
        defaultTableHead: DEFAULT_USAGER_TABLE_HEAD,
    };

    const tableManager = useTableManager<IPassengerList>(passengerConfig);

    const getFilterParams = () => {
        const filterParams: Record<string, string | number> = {};

        Object.entries(tableManager.filters).forEach(([key, { value }]) => {
            if((key === 'type' || key === 'state') && isValidFilterValue(value)) {
                const options = key === 'type' ? _RELATION_TYPE_OPTIONS : _PassengerStatus;
                filterParams[key] = getValue(value, options);
            }
            else if (isValidFilterValue(value)) {
                filterParams[key] = key === 'id' ? Number(value) : value;
            }
        });
        return filterParams;
    };

    useEffect(() => {
        const baseParams: SearchPassengerParams = {
            page: tableManager.table.page || 0,
            size: tableManager.table.rowsPerPage || 20,
            sortBy: tableManager.table.orderBy || 'id',
            sortDir: tableManager.table.order
        };

        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 searchPassengers(newParams, controller.signal);
            } catch (error: any) {
                if (!controller.signal.aborted) {
                    enqueueSnackbar(error.message || 'Erreur de chargement', {
                        variant: 'error'
                    });
                }
            }
        };

        const timer = setTimeout(fetchData, 300);

        return () => {
            controller.abort();
            clearTimeout(timer);
        };
    }, [
        tableManager.table.page,
        tableManager.table.rowsPerPage,
        tableManager.table.orderBy,
        tableManager.table.order,
        tableManager.filters
    ]);

    const handleExportPassengers = async () => {
        const filterParams = getFilterParams();
        const exportParams = { ...filterParams, userId: Number(localStorage.getItem('userId')) };

        try {
          await exportPassengers(exportParams);
          if (error == null) {
            enqueueSnackbar("Export des usagers est lancer avec succès!", { variant: 'success' });
          } else {
            enqueueSnackbar("Erreur lors de l'exportation des usagers.", { variant: 'error' });
          }
        } catch (error: any) {
          enqueueSnackbar(error.message || "Erreur lors de l'exportation des usagers", { variant: 'error' });
        }
      };

    return {
        ...tableManager,
        loading,
        error,
        totalPassengers: totalElements,
        handleExportPassengers,
        filteredData: passengers
    };
}
