import React from 'react';
import { Navigate, useLocation } from 'react-router-dom';
import { useAuth } from '../hooks/reduxHooks';
import { CircularProgress, Box } from '@mui/material';

/**
 * ProtectedRoute component to handle authenticated routes
 * 
 * @param {Object} props - Component props
 * @param {ReactNode} props.children - Child components to render when authenticated
 * @param {boolean} [props.requireAdmin=false] - Whether the route requires admin privileges
 * @param {string} [props.redirectTo='/auth/login'] - Where to redirect if not authenticated
 * @returns {ReactNode} The protected route
 */
const ProtectedRoute = ({ 
  children, 
  requireAdmin = false,
  redirectTo = '/auth/login' 
}) => {
  const { isAuthenticated, isAdmin, loading } = useAuth();
  const location = useLocation();

  // Show loading state
  if (loading) {
    return (
      <Box sx={{ display: 'flex', justifyContent: 'center', py: 8 }}>
        <CircularProgress />
      </Box>
    );
  }

  // Check authentication
  if (!isAuthenticated) {
    // Redirect to login, but save the current location so we can redirect back after login
    return <Navigate to={redirectTo} state={{ from: location }} replace />;
  }

  // Check admin privileges if required
  if (requireAdmin && !isAdmin) {
    // Redirect to home if not admin
    return <Navigate to="/" replace />;
  }

  // Render children if authenticated and has required privileges
  return children;
};

export default ProtectedRoute;