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

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

export const UserCardSelector: React.FC<UserCardSelectorProps> = ({
  userId,
  value,
  onChange,
  placeholder = "选择用户卡",
  disabled
}) => {
  const { data: cards, isLoading } = useQuery({
    queryKey: ['userCards', userId],
    queryFn: async () => {
      if (!userId) return [];
      
      const res = await userCardClient.$get({
        query: {
          page: 1,
          pageSize: 100,
          filters: JSON.stringify({ userId })
        }
      });
      
      if (res.status !== 200) throw new Error('获取用户卡列表失败');
      const result = await res.json();
      return result.data;
    },
    enabled: !!userId
  });

  return (
    <Select 
      value={value || ''} 
      onValueChange={onChange}
      disabled={disabled || isLoading}
    >
      <SelectTrigger>
        <SelectValue placeholder={placeholder} />
      </SelectTrigger>
      <SelectContent>
        {isLoading ? (
          <SelectItem value="loading" disabled>加载中...</SelectItem>
        ) : cards && cards.length > 0 ? (
          cards.map((card) => (
            <SelectItem key={card.id} value={card.cardNo}>
              {card.cardNo} (余额: ¥{card.balance.toFixed(2)})
            </SelectItem>
          ))
        ) : (
          <SelectItem value="no-cards" disabled>暂无用户卡</SelectItem>
        )}
      </SelectContent>
    </Select>
  );
};