import { useCallback, useEffect, useState } from 'react';
import { TableConfig, useTableManager } from '@/hooks/use-table-manager';
import { TableType } from '@/shared/types/common';
import { SearchTripParams, useCircuitStore } from '@/shared/api/stores/circuit-service/circuitStore';
import { TripCircuitDetails, TripCircuitDTO,  } from '@/shared/types/circuit';
import { enqueueSnackbar } from 'notistack';
import { DEFAULT_CIRCUIT_TRAJET_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 const getTripParams = (circuitId: string): SearchTripParams => ({
  circuitId,
  page: 0,
  size: 20,
});

export function useTrajetTable(circuitId: string, amendmentId?: string) {
  const [params, setParams] = useState<SearchTripParams>(getTripParams(circuitId));
  const { trips, loading, error, getTrips, totalElementsTrips } = useCircuitStore();

  const { getTripCircuitById, loadingDetailsRegular, getTripsWithTripPoints, tripsWithTripPoints, loadingTripsWithTripPoints, getAmendmentTripsWithTripPoints } = useTripCircuitStore();

  const trajetConfig: TableConfig<TripCircuitDTO> = {
    type: TableType.Trajet,
    initialData: amendmentId ? tripsWithTripPoints : trips || [],
    defaultTableHead: DEFAULT_CIRCUIT_TRAJET_TABLE_HEAD,
  };

  const tableManager = useTableManager<TripCircuitDTO>(trajetConfig);

  useEffect(() => {
    const baseParams: SearchTripParams = {
      circuitId,
      page: tableManager.table.page || 0,
      size: tableManager.table.rowsPerPage || 20,
    };

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

    const newParams: SearchTripParams = {
      ...filterParams,
      ...baseParams,
    };

    const paramsChanged = JSON.stringify(newParams) !== JSON.stringify(params);
    if (paramsChanged) {
      setParams(newParams);
    }
  // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [circuitId, tableManager.table.page, tableManager.filters, tableManager.table.rowsPerPage, tableManager.table.orderBy, tableManager.table.order]);

  useEffect(() => {
    const fetch = async () => {
      try {
        if(!amendmentId){
          await getTrips(params);
        }
      } catch (error: any) {
        enqueueSnackbar(error.message || 'Erreur lors de la recherche des trajets', { variant: 'error' });
      }
    };
    fetch();
  }, [params, getTrips, amendmentId]);
  useEffect(() => {
    const fetchTemporaryTrips = async () => {
      try {
        if (amendmentId) {
          await getAmendmentTripsWithTripPoints(amendmentId);
        } else {
          await getTripsWithTripPoints(circuitId);
        }
      } catch (error: any) {
        enqueueSnackbar(error.message || 'Erreur lors de la récupération des trajets temporaires', { variant: 'error' });
      }
    };
    fetchTemporaryTrips();
  }, [circuitId, amendmentId, getTripsWithTripPoints, getAmendmentTripsWithTripPoints]);
  
  const getTripCircuit = useCallback(
    async (id: string, handleView: (details: TripCircuitDetails) => void) => {
      try {
        const details = await getTripCircuitById(id, 'regular');
        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: loading || loadingTripsWithTripPoints,
    error,
    totalTrips: totalElementsTrips || 0,
    getTripCircuit,
    loadingDetails: loadingDetailsRegular,
    tripsWithTripPoints,
  };
}