import { useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { useAuthStore } from '../store/authStore';

export function useLogout() {
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<Error | null>(null);
  const navigate = useNavigate();
  const logoutStore = useAuthStore((state) => state.logout);

  const handleLogout = async () => {
    try {
      setLoading(true);
      setError(null);
      // Le store gère déjà le logout et le nettoyage des tokens
      await logoutStore();
      navigate('/login');
    } catch (err) {
      setError(err as Error);
      // Même en cas d'erreur, on nettoie l'état local
      navigate('/login');
    } finally {
      setLoading(false);
    }
  };

  return { handleLogout, loading, error };
}
