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 '@d8d/bank-name-management-ui/api';

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

export const BankSelect: React.FC<BankSelectProps> = ({
  value,
  onChange,
  placeholder = "请选择银行",
  disabled = false,
  className,
  testId = 'bank-select',
  allowCustomInput = false,
  onCustomInput,
}) => {
  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,
          filters: JSON.stringify({ status: 1}) // 只获取启用的银行名称
        }
      });
      if (res.status !== 200) throw new Error('获取银行名称失败');
      return await res.json();
    },
  });

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

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

  // 如果允许自定义输入，可以在这里添加自定义输入逻辑
  // 参考省份选择组件的实现

  return (
    <Select
      value={value?.toString()}
      onValueChange={(val) => {
        if (val === 'custom' && onCustomInput) {
          // 处理自定义输入
          const customValue = prompt('请输入银行名称:');
          if (customValue && onCustomInput) {
            onCustomInput(customValue);
          }
        } else {
          onChange?.(parseInt(val));
        }
      }}
      disabled={disabled || isLoading || banks.length === 0}
    >
      <SelectTrigger className={className} data-testid={testId}>
        <SelectValue placeholder={isLoading ? '加载中...' : placeholder} />
      </SelectTrigger>
      <SelectContent>
        {banks.map((bank) => (
          <SelectItem key={bank.id} value={bank.id.toString()}>
            {bank.name}
          </SelectItem>
        ))}
        {allowCustomInput && (
          <SelectItem value="custom" className="text-muted-foreground">
            + 自定义银行名称
          </SelectItem>
        )}
      </SelectContent>
    </Select>
  );
};

export default BankSelect;