'use client';

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

interface PermissionButtonProps extends React.ButtonHTMLAttributes<HTMLButtonElement> {
  requiredPermissions?: Permission[];
  anyPermission?: Permission[];
  hideWhenDisabled?: boolean;
}

export function PermissionButton({
  children,
  requiredPermissions,
  anyPermission,
  hideWhenDisabled = false,
  disabled,
  ...props
}: PermissionButtonProps) {
  const { user } = useAuth();

  const hasAccess = (): boolean => {
    if (!user) return false;

    const userRole = user.role as Role;

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

    if (anyPermission?.length) {
      if (!hasAnyPermission(userRole, anyPermission)) return false;
    }

    return true;
  };

  const canAccess = hasAccess();

  if (!canAccess && hideWhenDisabled) {
    return null;
  }

  return (
    <button {...props} disabled={disabled || !canAccess}>
      {children}
    </button>
  );
}
