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

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

export const AgentSelector: React.FC<AgentSelectorProps> = ({
  value,
  onChange,
  placeholder = "选择代理商",
  disabled
}) => {
  const { data: agents, isLoading } = useQuery({
    queryKey: ['agents'],
    queryFn: async () => {
      const res = await agentClient.$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>
        ) : agents && agents.length > 0 ? (
          agents.map((agent) => (
            <SelectItem key={agent.id} value={agent.id.toString()}>
              {agent.name || agent.username} ({agent.realname || agent.phone || '无联系方式'})
            </SelectItem>
          ))
        ) : (
          <SelectItem value="no-agents" disabled>暂无代理商</SelectItem>
        )}
      </SelectContent>
    </Select>
  );
};