import { useEffect, useRef } from 'react';
import { TableConfig, useTableManager } from '@/hooks/use-table-manager';
import {
  Circuit,
  circuitStateOptions,
  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 } = 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,
  ]);

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