import React from 'react';
import { useAuth } from '../../context/AuthContext';

interface PermissionButtonProps {
  permission?: string;
  permissions?: string[];
  requireAll?: boolean;
  children: React.ReactNode;
  className?: string;
  onClick?: () => void;
  disabled?: boolean;
  type?: 'button' | 'submit' | 'reset';
}

const PermissionButton: React.FC<PermissionButtonProps> = ({
  permission,
  permissions = [],
  requireAll = false,
  children,
  className = '',
  onClick,
  disabled = false,
  type = 'button',
  ...props
}) => {
  const { hasPermission, hasAnyPermission, hasAllPermissions } = useAuth();

  // Check if user has required permissions
  const hasRequiredPermissions = React.useMemo(() => {
    if (permission) {
      return hasPermission(permission);
    }
    
    if (permissions.length > 0) {
      return requireAll 
        ? hasAllPermissions(permissions)
        : hasAnyPermission(permissions);
    }
    
    return true; // No permission required
  }, [permission, permissions, requireAll, hasPermission, hasAnyPermission, hasAllPermissions]);

  // Don't render if user doesn't have required permissions
  if (!hasRequiredPermissions) {
    return null;
  }

  return (
    <button
      type={type}
      className={className}
      onClick={onClick}
      disabled={disabled}
      {...props}
    >
      {children}
    </button>
  );
};

interface PermissionDivProps {
  permission?: string;
  permissions?: string[];
  requireAll?: boolean;
  children: React.ReactNode;
  className?: string;
}

const PermissionDiv: React.FC<PermissionDivProps> = ({
  permission,
  permissions = [],
  requireAll = false,
  children,
  className = '',
  ...props
}) => {
  const { hasPermission, hasAnyPermission, hasAllPermissions } = useAuth();

  // Check if user has required permissions
  const hasRequiredPermissions = React.useMemo(() => {
    if (permission) {
      return hasPermission(permission);
    }
    
    if (permissions.length > 0) {
      return requireAll 
        ? hasAllPermissions(permissions)
        : hasAnyPermission(permissions);
    }
    
    return true; // No permission required
  }, [permission, permissions, requireAll, hasPermission, hasAnyPermission, hasAllPermissions]);

  // Don't render if user doesn't have required permissions
  if (!hasRequiredPermissions) {
    return null;
  }

  return (
    <div className={className} {...props}>
      {children}
    </div>
  );
};

// Alias for PermissionDiv as PermissionComponent
const PermissionComponent = PermissionDiv;

export { PermissionButton, PermissionDiv, PermissionComponent };
