import { ReactNode, useContext } from "react";
import { AuthContext } from "@/contexts/AuthContext";

interface ProtectedProps {
  // For specific permission code
  permission?: string;
  
  // For page access permission format: access:{page}
  page?: string;
  
  // For action permission format: {action}:{resource}
  resource?: string;
  action?: "view" | "create" | "edit" | "delete" | string;
  
  // For admin-only access
  adminOnly?: boolean;
  
  // Content to render if permission check passes
  children: ReactNode;
  
  // Optional fallback content
  fallback?: ReactNode;
}

/**
 * A simplified component that conditionally renders content based on user permissions
 */
export function Protected({
  permission,
  page,
  resource,
  action,
  adminOnly,
  children,
  fallback = null
}: ProtectedProps) {
  const { user } = useContext(AuthContext);
  
  // If user isn't loaded yet, don't render anything
  if (!user) {
    return null;
  }
  
  // Admin check - admins always have access to everything
  if (user.is_admin) {
    return <>{children}</>;
  }
  
  // Admin-only check
  if (adminOnly) {
    return <>{fallback}</>;
  }
  
  // Check permissions array exists
  if (!user.permissions) {
    return <>{fallback}</>;
  }
  
  // Page access check (access:page)
  if (page) {
    const pagePermission = `access:${page.toLowerCase()}`;
    if (!user.permissions.includes(pagePermission)) {
      return <>{fallback}</>;
    }
  }
  
  // Resource action check (action:resource)
  if (resource && action) {
    const resourcePermission = `${action}:${resource.toLowerCase()}`;
    if (!user.permissions.includes(resourcePermission)) {
      return <>{fallback}</>;
    }
  }
  
  // Single permission check
  if (permission && !user.permissions.includes(permission)) {
    return <>{fallback}</>;
  }
  
  // If all checks pass, render children
  return <>{children}</>;
} 