import { useAuth } from '../context/AuthContext';
import { hasAccess, type UserRole } from '../lib/navigation';

/**
 * Hook for checking user permissions
 */
export function usePermissions() {
    const { user } = useAuth();
    const userRole = (user?.role?.toUpperCase() || 'VIEWER') as UserRole;

    return {
        /**
         * Check if user has access to a resource with minRole requirement
         */
        canAccess: (minRole?: UserRole) => hasAccess(userRole, minRole),

        /**
         * Current user role
         */
        role: userRole,

        /**
         * Check specific permission flags
         */
        isAdmin: userRole === 'ADMIN' || userRole === 'OWNER',
        isManager: hasAccess(userRole, 'MANAGER'),
        isStaff: hasAccess(userRole, 'STAFF'),
        isViewer: userRole === 'VIEWER',

        /**
         * Get display-friendly role name
         */
        roleName: getRoleName(userRole),

        /**
         * Get role color classes for badges
         */
        roleColor: getRoleColor(userRole),
    };
}

function getRoleName(role: UserRole): string {
    const names: Record<UserRole, string> = {
        VIEWER: 'Viewer',
        STAFF: 'Staff',
        GROWER: 'Grower',
        MANAGER: 'Manager',
        ADMIN: 'Admin',
        OWNER: 'Owner',
    };
    return names[role] || role;
}

function getRoleColor(role: UserRole): string {
    const colors: Record<UserRole, string> = {
        VIEWER: 'bg-slate-100 text-slate-600 dark:bg-slate-700 dark:text-slate-300',
        STAFF: 'bg-blue-100 text-blue-700 dark:bg-blue-900/30 dark:text-blue-400',
        GROWER: 'bg-green-100 text-green-700 dark:bg-green-900/30 dark:text-green-400',
        MANAGER: 'bg-purple-100 text-purple-700 dark:bg-purple-900/30 dark:text-purple-400',
        ADMIN: 'bg-amber-100 text-amber-700 dark:bg-amber-900/30 dark:text-amber-400',
        OWNER: 'bg-emerald-100 text-emerald-700 dark:bg-emerald-900/30 dark:text-emerald-400',
    };
    return colors[role] || colors.VIEWER;
}
