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

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

const SupplierSelector: React.FC<SupplierSelectorProps> = ({
  value,
  onChange,
  placeholder = "请选择供应商",
  disabled = false,
}) => {
  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 data = await res.json();
      return data.data;
    },
    enabled: !disabled,
  });

  return (
    <Select
      value={value?.toString()}
      onValueChange={(v) => onChange?.(parseInt(v))}
      disabled={disabled || isLoading}
    >
      <SelectTrigger>
        <SelectValue placeholder={isLoading ? "加载中..." : placeholder} />
      </SelectTrigger>
      <SelectContent>
        {suppliers?.map((supplier) => (
          <SelectItem key={supplier.id} value={supplier.id.toString()}>
            {supplier.name}
          </SelectItem>
        ))}
      </SelectContent>
    </Select>
  );
};

export default SupplierSelector;