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';

export  const getAmendmentParams = (passengerId: number) => {
  const params: SearchPassengerAmendmentParams = {
    passengerId,
    page: 0,
    size: 20,
    sortBy: 'id',
    sortDir: 'DESC',
  };
  return params;
} 
export function useAmendmentPassengerCircuitTable(passengerId: number) {
  const [params, setParams] = useState<SearchPassengerAmendmentParams>(getAmendmentParams(passengerId));

  const { activeOrFutureAmendments, totalElements, loading, error, getActiveOrFutureAmendmentsByPassengerId, getAmendmentById } = useAmendmentPassengerStore();

  const amendmentConfig: TableConfig<AmendmentPassengerList> = {
    type: TableType.Avenant,
    initialData: activeOrFutureAmendments || [],
    defaultTableHead: DEFAULT_AMENDMENT_PASSENGER_CIRCUIT_TABLE_HEAD,
  };

  const tableManager = useTableManager<AmendmentPassengerList>(amendmentConfig);

  useEffect(() => {
    const baseParams: SearchPassengerAmendmentParams = {
      passengerId,
      page: tableManager.table.page || 0,
      size: tableManager.table.rowsPerPage || 20,
      sortBy: tableManager.table.orderBy || 'id',
      sortDir: tableManager.table.order?.toUpperCase() as 'ASC' | 'DESC',
    };

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

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

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

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

  const getAndViewAmendment = useCallback(
    async (AmendmentPassengerId: string, handleView: (details: AmendmentPassengerDetails) => void) => {
      try {
        const details = await getAmendmentById(AmendmentPassengerId);
        if (details) {
          handleView(details);
        }
      } catch (error: any) {
        enqueueSnackbar(error.message || 'Erreur lors de la récupération du détail', { variant: 'error' });
      }
    },
    [getAmendmentById]
  );

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