'use client';

import { useAuth } from '@/lib/hooks/useAuth';
import { Permission, hasPermission, hasAnyPermission, isAdmin, isSuperAdmin } from '@/lib/auth/roles';
import { Role } from '@/types/auth';

interface RoleGateProps {
  children: React.ReactNode;
  requiredPermissions?: Permission[];
  anyPermission?: Permission[];
  requireAdmin?: boolean;
  requireSuperAdmin?: boolean;
  fallback?: React.ReactNode;
}

export function RoleGate({
  children,
  requiredPermissions,
  anyPermission,
  requireAdmin,
  requireSuperAdmin,
  fallback = null,
}: RoleGateProps) {
  const { user } = useAuth();

  if (!user) return <>{fallback}</>;

  const userRole = user.role as Role;

  if (requireSuperAdmin && !isSuperAdmin(userRole)) return <>{fallback}</>;
  if (requireAdmin && !isAdmin(userRole)) return <>{fallback}</>;

  if (requiredPermissions?.length) {
    const hasAll = requiredPermissions.every(p => hasPermission(userRole, p));
    if (!hasAll) return <>{fallback}</>;
  }

  if (anyPermission?.length) {
    if (!hasAnyPermission(userRole, anyPermission)) return <>{fallback}</>;
  }

  return <>{children}</>;
}

// Convenience components
export function AdminOnly({ children, fallback }: { children: React.ReactNode; fallback?: React.ReactNode }) {
  return <RoleGate requireAdmin fallback={fallback}>{children}</RoleGate>;
}

export function SuperAdminOnly({ children, fallback }: { children: React.ReactNode; fallback?: React.ReactNode }) {
  return <RoleGate requireSuperAdmin fallback={fallback}>{children}</RoleGate>;
}
