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

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

export const UserSelector: React.FC<UserSelectorProps> = ({
  value,
  onChange,
  placeholder = "选择用户",
  disabled
}) => {
  const { data: users, isLoading } = useQuery({
    queryKey: ['users'],
    queryFn: async () => {
      const res = await userClient.$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>
        <SelectValue placeholder={placeholder} />
      </SelectTrigger>
      <SelectContent>
        {isLoading ? (
          <SelectItem value="loading" disabled>加载中...</SelectItem>
        ) : users && users.length > 0 ? (
          users.map((user) => (
            <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>
  );
};