import { useCallback, useEffect, useRef } from 'react';
import { TableConfig, useTableManager } from '@/hooks/use-table-manager';
import {
  Circuit,
  circuitStateOptions,
  ExportCircuitParams,
  ICircuit,
  SearchCircuitParams,
} from '@/shared/types/circuit';
import { useCircuitStore } from '@/shared/api/stores/circuit-service/circuitStore';
import { DEFAULT_CIRCUIT_TABLE_HEAD } from '@/shared/_mock/_circuit';
import { enqueueSnackbar } from 'notistack';
import { isValidFilterValue } from '@/utils/helper';
import { getValue } from '@/shared/_mock';

export function useCircuitTable() {
  const abortControllerRef = useRef<AbortController | null>(null);
  const { circuits, totalElements, loading, error, searchCircuit, exportCircuits } = useCircuitStore();

  const circuitConfig: TableConfig<Circuit> = {
    initialData: circuits || [],
    defaultTableHead: DEFAULT_CIRCUIT_TABLE_HEAD,
  };

  const tableManager = useTableManager<Circuit>(circuitConfig);

  // Fonction utilitaire pour générer les filtres
  const getFilterParams = () => {
    const filterParams: Record<string, string | number | boolean> = {};
    Object.entries(tableManager.filters).forEach(([key, { value }]) => {
      if (key === 'circuitState' && isValidFilterValue(value)) {
        const optionExists = circuitStateOptions.some((option) => option.label.toLowerCase() === value.toLowerCase());
        if (optionExists) {
          filterParams[key] = getValue(value, circuitStateOptions);
        }
      } else if (value !== undefined && value !== null && value !== '') {
        filterParams[key] = value;
      }
    });
    return filterParams;
  };

  useEffect(() => {
    const baseParams: SearchCircuitParams = {
      page: tableManager.table.page || 0,
      size: tableManager.table.rowsPerPage || 20,
      sortBy: tableManager.table.orderBy || 'id',
      sortDirection: 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 searchCircuit(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 handleExport = async () => {
    const filterParams = getFilterParams();

    try {
      const userIdString = localStorage.getItem('userId');
      if (userIdString) {
        const userId = Number(userIdString);

        const exportParams: ExportCircuitParams = {
          userId,
          ...filterParams
        };

        await exportCircuits(exportParams);
        if (error == null) {
          enqueueSnackbar('Export des circuits lancé avec succès!', { variant: 'success' });
        } else {
          enqueueSnackbar("Erreur lors de l'exportation des circuits.", { variant: 'error' });
        }
      }
    } catch (error) {
      enqueueSnackbar("Erreur lors de l'exportation des circuits.", { variant: 'error' });
    }
  };

  return {
    ...tableManager,
    loading,
    error,
    totalCircuits: totalElements,
    filteredData: circuits,
    handleExport
  };
}
