import React, { useEffect } from 'react';
import { useNavigate, useLocation } from 'react-router-dom';
import { useAuth } from '../../hooks/useAuth';
import LoadingSpinner from '../UI/LoadingSpinner';

const TokenHandler = () => {
  const { refreshToken } = useAuth();
  const navigate = useNavigate();
  const location = useLocation();
  
  useEffect(() => {
    const handleToken = async () => {
      try {
        await refreshToken();
        // Redirect to the intended page or dashboard
        const redirectTo = new URLSearchParams(location.search).get('redirect') || '/dashboard';
        navigate(redirectTo, { replace: true });
      } catch (error) {
        console.error('Token refresh error:', error);
        navigate('/login', { replace: true });
      }
    };
    
    handleToken();
  }, [refreshToken, navigate, location]);

  return (
    <div style={{ display: 'flex', justifyContent: 'center', alignItems: 'center', height: '100vh' }}>
      <LoadingSpinner message="Authenticating..." />
    </div>
  );
};

export default TokenHandler;