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 { supplierClient } from '../api/supplierClient';

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

export const SupplierSelector: React.FC<SupplierSelectorProps> = ({
  value,
  onChange,
  placeholder = "选择供应商",
  disabled,
  testId
}) => {
  const { data: suppliers, isLoading } = useQuery({
    queryKey: ['suppliers'],
    queryFn: async () => {
      const res = await supplierClient.$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>
        ) : suppliers && suppliers.length > 0 ? (
          suppliers.map((supplier) => (
            <SelectItem key={supplier.id} value={supplier.id.toString()}>
              {supplier.name}
            </SelectItem>
          ))
        ) : (
          <SelectItem value="no-suppliers" disabled>暂无供应商</SelectItem>
        )}
      </SelectContent>
    </Select>
  );
};