import { useQuery } from '@tanstack/react-query';
import { useCallback } from 'react';
import { supabase } from '@/lib/supabaseClient';
import { useAuth } from '@/hooks/useAuth';
import { queryKeys } from '@/lib/queryKeys';
import { handleNonCriticalError } from '@/lib/errorHandler';

export type UserRole = 'admin' | 'moderator' | 'user' | 'superuser';

export interface UserPermissions {
  can_ban_any_user: boolean;
  can_manage_admin_roles: boolean;
  can_manage_moderator_roles: boolean;
  can_view_all_profiles: boolean;
  can_assign_superuser: boolean;
  role_level: string;
}

export function useUserRole() {
  const { user } = useAuth();

  // Fetch user roles with TanStack Query for automatic caching
  const rolesQuery = useQuery({
    queryKey: queryKeys.userRoles(user?.id),
    queryFn: async () => {
      if (!user) return [];
      
      const { data, error } = await supabase
        .from('user_roles')
        .select('role')
        .eq('user_id', user.id);
      
      if (error) {
        handleNonCriticalError(error, {
          action: 'Fetch user roles',
          userId: user.id,
        });
        return [];
      }
      
      return data?.map(r => r.role as UserRole) || [];
    },
    enabled: !!user,
    staleTime: 5 * 60 * 1000, // 5 minutes - roles don't change often
    gcTime: 10 * 60 * 1000,    // 10 minutes garbage collection
  });

  // Fetch user permissions with TanStack Query for automatic caching
  const permissionsQuery = useQuery({
    queryKey: queryKeys.userPermissions(user?.id),
    queryFn: async () => {
      if (!user) return null;
      
      const { data, error } = await supabase
        .rpc('get_user_management_permissions', { _user_id: user.id });
      
      if (error) {
        handleNonCriticalError(error, {
          action: 'Fetch user permissions',
          userId: user.id,
        });
        return null;
      }
      
      return data as unknown as UserPermissions;
    },
    enabled: !!user,
    staleTime: 5 * 60 * 1000, // 5 minutes - permissions don't change often
    gcTime: 10 * 60 * 1000,    // 10 minutes garbage collection
  });

  const roles = rolesQuery.data || [];
  const permissions = permissionsQuery.data || null;
  const loading = rolesQuery.isLoading || permissionsQuery.isLoading;

  const hasRole = useCallback((role: UserRole) => roles.includes(role), [roles]);
  const isModerator = useCallback(() => hasRole('admin') || hasRole('moderator') || hasRole('superuser'), [hasRole]);
  const isAdmin = useCallback(() => hasRole('admin') || hasRole('superuser'), [hasRole]);
  const isSuperuser = useCallback(() => hasRole('superuser'), [hasRole]);

  return {
    roles,
    permissions,
    loading,
    hasRole,
    isModerator,
    isAdmin,
    isSuperuser
  };
}