import React from 'react';
import { useQuery } from '@tanstack/react-query';
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '@d8d/shared-ui-components/components/ui/select';
import { userClientManager } from '../api/userClient';

interface UserSelectorProps {
  value?: number;
  onChange?: (value: number) => void;
  placeholder?: string;
  disabled?: boolean;
  testId?: string;
}

export const UserSelector: React.FC<UserSelectorProps> = ({
  value,
  onChange,
  placeholder = "选择用户",
  disabled,
  testId
}) => {
  const { data: users, isLoading } = useQuery({
    queryKey: ['users'],
    queryFn: async () => {
      const userClient = userClientManager.get();
      const res = await userClient.index.$get({
        query: {
          page: 1,
          pageSize: 100
        }
      });

      if (res.status !== 200) throw new Error('获取用户列表失败');
      const result = await res.json();
      return result.data;
    }
  });

  return (
    <Select
      value={value?.toString() || ''}
      onValueChange={(val) => onChange?.(parseInt(val))}
      disabled={disabled || isLoading}
    >
      <SelectTrigger data-testid={testId}>
        <SelectValue placeholder={placeholder} />
      </SelectTrigger>
      <SelectContent>
        {isLoading ? (
          <SelectItem value="loading" disabled>加载中...</SelectItem>
        ) : users && users.length > 0 ? (
          users.map((user: any) => (
            <SelectItem key={user.id} value={user.id.toString()}>
              {user.name || user.username} ({user.phone || user.email})
            </SelectItem>
          ))
        ) : (
          <SelectItem value="no-users" disabled>暂无用户</SelectItem>
        )}
      </SelectContent>
    </Select>
  );
};