import { TabConfig, useTabsManager } from '../../../../hooks/use-tabs-manager';
import { TableType } from '@/shared/types/common';
import { AmendmentPassengerDetails } from '@/shared/types/ammendment-passenger';
import { usePassengerStore } from '@/shared/api/stores/passengerStore';
import { useAmendmentPassengerStore } from '@/shared/api/stores/circuit-service/amendmentPassengerStore';
import { useEffect, useState } from 'react';
import { enqueueSnackbar } from 'notistack';
import { INITIAL_AVENANT_USAGERS_DATA } from '@/shared/_mock/_avenantUsager';

export function useAmendmentPassengerTabs(passengerId: number) {
  const { getInitialAmendmentByPassengerId } = useAmendmentPassengerStore();
  const [initialData, setInitialData] = useState<AmendmentPassengerDetails | null>(null);
  const [isLoading, setIsLoading] = useState(true);

  useEffect(() => {
    let cancelled = false;
  
    const loadInitialData = async () => {
      if (!passengerId) {
        setIsLoading(false);
        return;
      }
  
      setIsLoading(true);
  
      try {
        const initialScheduleData = await getInitialAmendmentByPassengerId(passengerId);
  
        const enrichedAvenant: AmendmentPassengerDetails = {
          ...INITIAL_AVENANT_USAGERS_DATA,
          passengerId,
          amendmentRepresentatives: initialScheduleData?.amendmentRepresentatives ?? [],
          establishmentWeekPassengerMap: initialScheduleData?.establishmentWeekPassengerMap ?? [],
          passengerScheduleWeeks: initialScheduleData?.passengerScheduleWeeks ?? [],
          startDate: initialScheduleData?.startDate ?? '',
          endDate: initialScheduleData?.endDate ?? '',
        };
  
        if (!cancelled) {
          setInitialData(enrichedAvenant);
        }
      } catch (err) {
        if (!cancelled) {
          enqueueSnackbar("Erreur lors du Chargement du dernier avenant usager", { variant: "warning" });
  
          setInitialData({
            ...INITIAL_AVENANT_USAGERS_DATA,
            passengerId,
            passengerScheduleWeeks: [],
          });
        }
      } finally {
        if (!cancelled) setIsLoading(false);
      }
    };
  
    loadInitialData();
  
    return () => {
      cancelled = true;
    };
  }, [passengerId, getInitialAmendmentByPassengerId]);

  const avenantTabsConfig: TabConfig<AmendmentPassengerDetails> = {
    type: TableType.Avenant,
    listTitle: 'Liste des avenants',
    newItemTitle: 'Nouveau avenant',
    initialData: initialData || INITIAL_AVENANT_USAGERS_DATA,
    getItemCode: (avenant) => avenant.id,
  };

  const tabsManager = useTabsManager<AmendmentPassengerDetails>(avenantTabsConfig);
  
  return {
    ...tabsManager,
    isLoading,
  };
}

