import React from 'react';
import { usePermissions } from '../src/hooks/usePermissions';

interface PermissionGateProps {
  /** 需要的权限（OR 关系：有任一即可） */
  permission?: string;
  /** 多个权限 OR 关系 */
  any?: string[];
  /** 多个权限 AND 关系（必须全部拥有） */
  all?: string[];
  /** 加载中时显示的内容（默认不显示） */
  fallback?: React.ReactNode;
  /** 无权限时显示的内容（默认不显示） */
  denied?: React.ReactNode;
  children: React.ReactNode;
}

/**
 * 组件级权限门控
 * 根据用户权限集有条件的渲染子组件
 *
 * @example
 * ```tsx
 * <PermissionGate permission="user:create">
 *   <Button>创建用户</Button>
 * </PermissionGate>
 *
 * <PermissionGate any={['user:edit', 'user:delete']}>
 *   <AdminPanel />
 * </PermissionGate>
 * ```
 */
export const PermissionGate: React.FC<PermissionGateProps> = ({
  permission,
  any,
  all,
  fallback = null,
  denied = null,
  children,
}) => {
  const { hasPermission, hasAnyPermission, hasAllPermissions, isLoading } = usePermissions();

  if (isLoading) {
    return <>{fallback}</>;
  }

  let granted = false;

  if (permission) {
    granted = hasPermission(permission);
  } else if (any && any.length > 0) {
    granted = hasAnyPermission(...any);
  } else if (all && all.length > 0) {
    granted = hasAllPermissions(...all);
  } else {
    // 没有指定权限要求 → 放行
    granted = true;
  }

  return <>{granted ? children : denied}</>;
};
