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

type Merchant = InferResponseType<typeof merchantClient.$get, 200>['data'][0];

interface MerchantSelectorProps {
  value?: number;
  onChange?: (value: number | undefined) => void;
  placeholder?: string;
  disabled?: boolean;
  allowClear?: boolean;
}

export const MerchantSelector: React.FC<MerchantSelectorProps> = ({
  value,
  onChange,
  placeholder = '选择商户',
  disabled = false,
  allowClear = true,
}) => {
  const { data, isLoading } = useQuery({
    queryKey: ['merchants-select'],
    queryFn: async () => {
      const res = await merchantClient.$get({
        query: { page: 1, pageSize: 100 }
      });
      if (res.status !== 200) throw new Error('获取商户列表失败');
      return await res.json();
    },
  });

  const merchants = data?.data || [];

  const handleValueChange = (newValue: string) => {
    const numValue = newValue === 'null' ? undefined : parseInt(newValue, 10);
    onChange?.(numValue);
  };

  return (
    <Select
      value={value?.toString() || (allowClear ? 'null' : undefined)}
      onValueChange={handleValueChange}
      disabled={disabled}
    >
      <SelectTrigger>
        <SelectValue placeholder={placeholder} />
      </SelectTrigger>
      <SelectContent>
        {allowClear && (
          <SelectItem value="null">无</SelectItem>
        )}
        {merchants.map((merchant) => (
          <SelectItem key={merchant.id} value={merchant.id.toString()}>
            {merchant.name || merchant.username}
          </SelectItem>
        ))}
      </SelectContent>
    </Select>
  );
};

export default MerchantSelector;