import { useState, useEffect, useCallback } from 'react';
import { useSnackbar } from 'notistack';
import { tripsApi } from '@/shared/api/endpoints/hr/trips';
import type { Department } from '@/shared/api/endpoints/hr/candidates';

export const useDepartments = () => {
  const { enqueueSnackbar } = useSnackbar();
  const [departments, setDepartments] = useState<Department[]>([]);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);

  const fetchDepartments = useCallback(async () => {
    setLoading(true);
    setError(null);
    
    try {
      const data = await tripsApi.getDepartments();
      setDepartments(data);
      return data;
    } catch (error: any) {
      console.error('Error fetching departments:', error);
      setError(error.message || 'Erreur lors du chargement des départements');
      enqueueSnackbar('Erreur lors du chargement des départements', { variant: 'error' });
      return [];
    } finally {
      setLoading(false);
    }
  }, [enqueueSnackbar]);

  useEffect(() => {
    fetchDepartments();
  }, [fetchDepartments]);

  return {
    departments,
    loading,
    error,
    refetch: fetchDepartments,
  };
};
