import { useState, useEffect } from 'react';
import { supabase } from '@/integrations/supabase/client';
import { useAuth } from '@/hooks/useAuth';

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();
  const [roles, setRoles] = useState<UserRole[]>([]);
  const [permissions, setPermissions] = useState<UserPermissions | null>(null);
  const [loading, setLoading] = useState(true);

  useEffect(() => {
    if (!user) {
      setRoles([]);
      setLoading(false);
      return;
    }

    const fetchRoles = async () => {
      try {
        // Fetch user roles
        const { data: rolesData, error: rolesError } = await supabase
          .from('user_roles')
          .select('role')
          .eq('user_id', user.id);

        if (rolesError) {
          console.error('Error fetching user roles:', rolesError);
          setRoles([]);
        } else {
          setRoles(rolesData?.map(r => r.role as UserRole) || []);
        }

        // Fetch user permissions using the new function
        const { data: permissionsData, error: permissionsError } = await supabase
          .rpc('get_user_management_permissions', { _user_id: user.id });

        if (permissionsError) {
          console.error('Error fetching user permissions:', permissionsError);
          setPermissions(null);
        } else {
          setPermissions(permissionsData as unknown as UserPermissions);
        }
      } catch (error: unknown) {
        console.error('Error fetching user roles:', error);
        setRoles([]);
        setPermissions(null);
      } finally {
        setLoading(false);
      }
    };

    fetchRoles();
  }, [user]);

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

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