import { TableConfig, useTableManager } from '@/hooks/use-table-manager';
import { TableType } from '@/shared/types/common';
import { useAmendmentPassengerStore } from '@/shared/api/stores/circuit-service/amendmentPassengerStore';
import { useEffect, useState, useCallback } from 'react';
import { AmendmentPassengerList, AmendmentPassengerDetails, SearchPassengerAmendmentParams } from '@/shared/types/ammendment-passenger';
import { enqueueSnackbar } from 'notistack';
import { DEFAULT_AMENDMENT_PASSENGER_CIRCUIT_TABLE_HEAD, DEFAULT_AMENDMENT_PASSENGER_TABLE_HEAD } from '@/shared/_mock/_avenantUsager';
import { useAmendmentCircuitStore } from '@/shared/api/stores/circuit-service/amendmentCircuitStore';
import { AmendmentCircuit, SearchAmendmentCircuitParams } from '@/shared/types/ammendment-circuit';
import { DEFAULT_AVENANT_CIRCUIT_TABLE_HEAD } from '@/shared/_mock/_avenants';

export  const getAmendmentParams = (circuitId: string) => {
  const params: SearchAmendmentCircuitParams = {
    circuitId,
    page: 0,
    size: 20,
  };
  return params;
} 
export function useAmendmentCircuitTable(circuitId: string) {
  const [params, setParams] = useState<SearchAmendmentCircuitParams>(getAmendmentParams(circuitId));

  const { circuitAmendments, loading, error, getAmendmentsByCircuitId, totalElements } = useAmendmentCircuitStore();

  const amendmentConfig: TableConfig<AmendmentCircuit> = {
    type: TableType.Avenant,
    initialData: circuitAmendments || [],
    defaultTableHead: DEFAULT_AVENANT_CIRCUIT_TABLE_HEAD,
  };

  const tableManager = useTableManager<AmendmentCircuit>(amendmentConfig);

  useEffect(() => {
    const baseParams: SearchAmendmentCircuitParams = {
      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: SearchAmendmentCircuitParams = {
      ...filterParams,
      ...baseParams,
    };

    const paramsChanged = JSON.stringify(newParams) !== JSON.stringify(params);
    if (paramsChanged) {
      setParams(newParams);
    }
  }, [circuitId, tableManager.table.page, tableManager.filters, tableManager.table.rowsPerPage, tableManager.table.orderBy, tableManager.table.order]);

  useEffect(() => {
    const fetch = async () => {
      try {
        await getAmendmentsByCircuitId(params);
      } catch (error: any) {
        enqueueSnackbar(error.message || 'Erreur lors de la recherche des avenants', { variant: 'error' });
      }
    };
    fetch();
    }, [params, getAmendmentsByCircuitId]);


  return {
    ...tableManager,
    loading,
    error,
    totalAmendments: totalElements || 0,
  };
}
