import type { ReactNode } from 'react';
import { Navigate } from 'react-router-dom';
import { useAuth } from '../../contexts/AuthContext';
import { Loading } from '../ui/Loading';
import type { UserRole } from '../../types/user';

interface ProtectedRouteProps {
  children: ReactNode;
  requiredRole?: UserRole;
}

export function ProtectedRoute({ children, requiredRole }: ProtectedRouteProps) {
  const { user, loading, isAuthenticated } = useAuth();

  if (loading) return <Loading fullScreen text="Loading your workspace..." />;

  if (!isAuthenticated) return <Navigate to="/login" replace />;

  if (requiredRole && user?.role !== requiredRole) {
    const redirectPath =
      user?.role === 'INFLUENCER'
        ? '/influencer/dashboard'
        : '/business/dashboard';
    return <Navigate to={redirectPath} replace />;
  }

  return <>{children}</>;
}
