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

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

export const BankNameSelector: React.FC<BankNameSelectorProps> = ({
  value,
  onChange,
  placeholder = "请选择银行名称",
  disabled = false,
  className,
  testId,
}) => {
  const {
    data: bankNames,
    isLoading,
    isError,
  } = useQuery({
    queryKey: ['bank-names'],
    queryFn: async () => {
      const client = bankNameClientManager.get()
      const res = await client.index.$get({
        query: {
          page: 1,
          pageSize: 100
        }
      });
      if (res.status !== 200) throw new Error('获取银行名称失败');
      return await res.json();
    },
  });

  if (isError) {
    return (
      <div className="text-sm text-destructive">
        加载银行名称失败
      </div>
    );
  }

  const types = bankNames?.data || [];

  return (
    <Select
      value={value?.toString()}
      onValueChange={(val) => onChange?.(parseInt(val))}
      disabled={disabled || isLoading || types.length === 0}
    >
      <SelectTrigger className={className} data-testid={testId}>
        <SelectValue placeholder={isLoading ? '加载中...' : placeholder} />
      </SelectTrigger>
      <SelectContent>
        {types.map((type) => (
          <SelectItem key={type.id} value={type.id.toString()}>
            {type.name}
          </SelectItem>
        ))}
      </SelectContent>
    </Select>
  );
};

export default BankNameSelector;