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

const STAFF_ROLES = ['admin', 'manager', 'employee', 'staff'];

export function useStaffUsers() {
  const [users, setUsers] = useState([]);
  const [loading, setLoading] = useState(true);

  const fetchStaffUsers = useCallback(async () => {
    setLoading(true);
    try {
      // Get user_ids that have a staff role
      const { data: roleRows, error: roleError } = await supabase
        .from('user_roles')
        .select('user_id, role')
        .in('role', STAFF_ROLES);

      if (roleError) throw roleError;

      const staffUserIds = [...new Set((roleRows || []).map(r => r.user_id))];
      if (staffUserIds.length === 0) { setUsers([]); setLoading(false); return; }

      const { data: profiles, error: profileError } = await supabase
        .from('profiles')
        .select('user_id, full_name, avatar_url')
        .in('user_id', staffUserIds);

      if (profileError) throw profileError;

      setUsers((profiles || []).map(p => ({
        id: p.user_id,
        name: p.full_name || 'Unknown User',
        avatar_url: p.avatar_url,
      })));
    } catch (err) {
      console.error('[useStaffUsers] Error:', err);
    } finally {
      setLoading(false);
    }
  }, []);

  useEffect(() => { fetchStaffUsers(); }, [fetchStaffUsers]);

  return { users, loading, refresh: fetchStaffUsers };
}
