import { useState, useCallback } from 'react';
import { useSnackbar } from 'notistack';
import { tripsApi } from '@/shared/api/endpoints/hr/trips';
import type { TripShortDTO } from '@/shared/types/trip';

export const useTrips = () => {
  const { enqueueSnackbar } = useSnackbar();
  const [loading, setLoading] = useState(false);
  const [trips, setTrips] = useState<TripShortDTO[]>([]);
  const [error, setError] = useState<string | null>(null);

  const getShortTripsByDriver = useCallback(async (driverId: number): Promise<TripShortDTO[]> => {
    setLoading(true);
    setError(null);
    
    try {
      const response = await tripsApi.getShortTripsByDriver(driverId);
      setTrips(response.data);
      return response.data;
    } catch (error: any) {
      console.error('Error fetching trips by driver:', error);
      setError(error.message || 'Erreur lors du chargement des trajets');
      enqueueSnackbar('Erreur lors du chargement des trajets', { variant: 'error' });
      return [];
    } finally {
      setLoading(false);
    }
  }, [enqueueSnackbar]);

  const clearTrips = useCallback(() => {
    setTrips([]);
    setError(null);
  }, []);

  return {
    loading,
    trips,
    error,
    getShortTripsByDriver,
    clearTrips,
  };
};
