import React from 'react';
import { Navigate, useLocation } from 'react-router-dom';
import { useAuth } from '../context/AuthContext';

interface ProtectedRouteProps {
  children: React.ReactNode;
  permission?: string;
  permissions?: string[];
  requireAll?: boolean; // If true, user needs ALL permissions; if false, user needs ANY permission
  fallbackPath?: string;
}

const ProtectedRoute: React.FC<ProtectedRouteProps> = ({
  children,
  permission,
  permissions = [],
  requireAll = false,
  fallbackPath = '/dashboard'
}) => {
  const { isAuthenticated, hasPermission, hasAnyPermission, hasAllPermissions, isLoading } = useAuth();
  const location = useLocation();

  // Show loading spinner while authentication is being checked
  if (isLoading) {
    return (
      <div className="min-h-screen flex items-center justify-center">
        <div className="animate-spin rounded-full h-32 w-32 border-b-2 border-blue-600"></div>
      </div>
    );
  }

  // If not authenticated, redirect to login with current location preserved
  if (!isAuthenticated) {
    return <Navigate to="/login" state={{ from: location }} replace />;
  }

  // Check single permission
  if (permission && !hasPermission(permission)) {
    // Instead of redirecting, show access denied message or redirect to a safe page
    // Only redirect if user doesn't have basic dashboard access
    if (!hasPermission('dashboard.view')) {
      return <Navigate to={fallbackPath} replace />;
    }
    // If user has dashboard access but not this specific permission, 
    // redirect to dashboard instead of staying on current page
    return <Navigate to={fallbackPath} replace />;
  }

  // Check multiple permissions
  if (permissions.length > 0) {
    const hasRequiredPermissions = requireAll 
      ? hasAllPermissions(permissions)
      : hasAnyPermission(permissions);
    
    if (!hasRequiredPermissions) {
      // Only redirect if user doesn't have basic dashboard access
      if (!hasPermission('dashboard.view')) {
        return <Navigate to={fallbackPath} replace />;
      }
      // If user has dashboard access but not these specific permissions, 
      // redirect to dashboard instead of staying on current page
      return <Navigate to={fallbackPath} replace />;
    }
  }

  return <>{children}</>;
};

export default ProtectedRoute;
