'use client';

import { ReactNode } from 'react';
import { useAuth } from '@/hooks/useAuth';
import { UserRole, ROLE_PERMISSIONS } from '@/types/auth';

interface PermissionCheckProps {
  children: ReactNode;
  requiredRoles?: UserRole[];
  requiredPermission?: string;
  fallback?: ReactNode;
  showFallback?: boolean;
}

/**
 * Componente para verificar permissões específicas dentro de uma página
 */
export const PermissionCheck = ({
  children,
  requiredRoles,
  requiredPermission,
  fallback = null,
  showFallback = false
}: PermissionCheckProps) => {
  const { userRole, canAccess } = useAuth();

  // Verificar se tem o role necessário
  if (requiredRoles && !canAccess(requiredRoles)) {
    return showFallback ? <>{fallback}</> : null;
  }

  // Verificar permissão específica
  if (requiredPermission && userRole) {
    const permissions = ROLE_PERMISSIONS[userRole];
    if (!permissions || !(permissions as any)[requiredPermission]) {
      return showFallback ? <>{fallback}</> : null;
    }
  }

  return <>{children}</>;
};

/**
 * Hook para verificar permissões de forma programática
 */
export const usePermissions = () => {
  const { userRole, canAccess } = useAuth();

  const hasPermission = (permission: string): boolean => {
    if (!userRole) return false;
    const permissions = ROLE_PERMISSIONS[userRole];
    return permissions ? (permissions as any)[permission] === true : false;
  };

  const canAccessUsers = (): boolean => hasPermission('canAccessUsers');
  const canAccessAddresses = (): boolean => hasPermission('canAccessAddresses');
  const canAccessCompanies = (): boolean => hasPermission('canAccessCompanies');
  const canAccessDeliveries = (): boolean => hasPermission('canAccessDeliveries');
  const canAccessDashboard = (): boolean => hasPermission('canAccessDashboard');
  const canAccessProducts = (): boolean => hasPermission('canAccessProducts');
  const canAccessOrders = (): boolean => hasPermission('canAccessOrders');
  const canAccessPayments = (): boolean => hasPermission('canAccessPayments');
  const canAccessReports = (): boolean => hasPermission('canAccessReports');

  return {
    userRole,
    hasPermission,
    canAccess,
    canAccessUsers,
    canAccessAddresses,
    canAccessCompanies,
    canAccessDeliveries,
    canAccessDashboard,
    canAccessProducts,
    canAccessOrders,
    canAccessPayments,
    canAccessReports
  };
};