import React, { useState, useEffect } from 'react';
import { Button } from '@d8d/shared-ui-components/components/ui/button';
import { Card, CardContent } from '@d8d/shared-ui-components/components/ui/card';
import { Label } from '@d8d/shared-ui-components/components/ui/label';
import { Input } from '@d8d/shared-ui-components/components/ui/input';
import { Switch } from '@d8d/shared-ui-components/components/ui/switch';
import {
  Select,
  SelectContent,
  SelectItem,
  SelectTrigger,
  SelectValue,
} from '@d8d/shared-ui-components/components/ui/select';
import { Plus, Trash2, CreditCard } from 'lucide-react';
import { FileSelector } from '@d8d/file-management-ui/components';
import { BankSelect } from './BankSelect';
import { toast } from 'sonner';

// 银行卡类型枚举
export enum BankCardType {
  FIRST_CLASS = '一类卡',
  SECOND_CLASS = '二类卡'
}

export interface BankCardItem {
  subBankName: string;
  bankNameId: number | null;
  bankName?: string; // 保留用于向后兼容
  cardNumber: string;
  cardholderName: string;
  cardType?: BankCardType | string | null;
  fileId: number | null;
  isDefault: number;
  tempId?: string; // 临时ID用于React key
}

export interface BankCardManagementProps {
  value?: BankCardItem[];
  onChange?: (bankCards: BankCardItem[]) => void;
  maxCards?: number;
}

export const BankCardManagement: React.FC<BankCardManagementProps> = ({
  value = [],
  onChange,
  maxCards = 5,
}) => {
  const [bankCards, setBankCards] = useState<BankCardItem[]>(value);

  // 同步外部value变化
  useEffect(() => {
    setBankCards(value);
  }, [value]);

  const handleAddBankCard = () => {
    if (bankCards.length >= maxCards) {
      toast.warning(`最多只能添加 ${maxCards} 张银行卡`);
      return;
    }

    const newBankCard: BankCardItem = {
      subBankName: '',
      bankNameId: null,
      bankName: '',
      cardNumber: '',
      cardholderName: '',
      cardType: null,
      fileId: null,
      isDefault: 0,
      tempId: `temp-${Date.now()}-${Math.random()}`,
    };

    const newBankCards = [...bankCards, newBankCard];
    setBankCards(newBankCards);
    onChange?.(newBankCards);
  };

  const handleRemoveBankCard = (index: number) => {
    const newBankCards = bankCards.filter((_, i) => i !== index);
    setBankCards(newBankCards);
    onChange?.(newBankCards);
  };

  const handleFieldChange = (index: number, field: keyof BankCardItem, value: string | number | null) => {
    const newBankCards = [...bankCards];
    newBankCards[index] = { ...newBankCards[index], [field]: value };

    // 如果设置为默认银行卡，其他银行卡取消默认状态
    if (field === 'isDefault' && value === 1) {
      newBankCards.forEach((card, i) => {
        if (i !== index) {
          card.isDefault = 0;
        }
      });
    }

    setBankCards(newBankCards);
    onChange?.(newBankCards);
  };

  const handleFileIdChange = (index: number, fileId: number | null) => {
    console.debug(`handleFileIdChange called: index=${index}, fileId=${fileId}`);
    const newBankCards = [...bankCards];
    newBankCards[index] = { ...newBankCards[index], fileId };
    setBankCards(newBankCards);
    onChange?.(newBankCards);
  };

  const validateCardNumber = (cardNumber: string) => {
    // 简单的银行卡号验证：16-19位数字
    const cardNumberRegex = /^\d{16,19}$/;
    return cardNumberRegex.test(cardNumber.replace(/\s/g, ''));
  };

  const formatCardNumber = (cardNumber: string) => {
    // 格式化银行卡号：每4位加空格
    return cardNumber.replace(/\s/g, '').replace(/(\d{4})/g, '$1 ').trim();
  };

  return (
    <div className="space-y-4">
      <div className="flex items-center justify-between">
        <Label>银行卡管理</Label>
        <Button
          type="button"
          variant="outline"
          size="sm"
          onClick={handleAddBankCard}
          disabled={bankCards.length >= maxCards}
          data-testid="add-bank-card-button"
        >
          <Plus className="h-4 w-4 mr-2" />
          添加银行卡
        </Button>
      </div>

      {bankCards.length === 0 ? (
        <Card>
          <CardContent className="pt-6">
            <div className="flex flex-col items-center justify-center py-8 text-center">
              <CreditCard className="h-12 w-12 text-muted-foreground mb-4" />
              <p className="text-sm text-muted-foreground">暂无银行卡信息</p>
              <p className="text-xs text-muted-foreground mt-1">点击"添加银行卡"按钮添加银行卡信息</p>
            </div>
          </CardContent>
        </Card>
      ) : (
        <div className="space-y-4">
          {bankCards.map((card, index) => (
            <Card key={card.tempId || index} className="relative">
              <CardContent className="pt-6">
                <div className="absolute top-4 right-4">
                  <Button
                    type="button"
                    variant="ghost"
                    size="sm"
                    onClick={() => handleRemoveBankCard(index)}
                    data-testid={`remove-bank-card-${index}`}
                  >
                    <Trash2 className="h-4 w-4 text-destructive" />
                  </Button>
                </div>

                <div className="grid grid-cols-1 md:grid-cols-2 gap-4">
                  <div className="space-y-2">
                    <Label htmlFor={`bankNameId-${index}`}>银行名称 *</Label>
                    <BankSelect
                      value={card.bankNameId || undefined}
                      onChange={(value) => handleFieldChange(index, 'bankNameId', value)}
                      placeholder="请选择银行"
                      testId={`bank-select-${index}`}
                      allowCustomInput={true}
                      onCustomInput={(customValue) => {
                        // 处理自定义银行名称
                        // 这里可以调用API创建新的银行名称，然后设置bankNameId
                        toast.info(`自定义银行名称: ${customValue}，需要先创建银行名称`);
                      }}
                    />
                  </div>

                  <div className="space-y-2">
                    <Label htmlFor={`subBankName-${index}`}>发卡支行 *</Label>
                    <Input
                      id={`subBankName-${index}`}
                      value={card.subBankName}
                      onChange={(e) => handleFieldChange(index, 'subBankName', e.target.value)}
                      placeholder="例如：北京分行朝阳支行"
                      data-testid={`sub-bank-name-input-${index}`}
                    />
                  </div>

                  <div className="space-y-2">
                    <Label htmlFor={`cardNumber-${index}`}>银行卡号 *</Label>
                    <Input
                      id={`cardNumber-${index}`}
                      value={formatCardNumber(card.cardNumber)}
                      onChange={(e) => {
                        const rawValue = e.target.value.replace(/\s/g, '');
                        handleFieldChange(index, 'cardNumber', rawValue);
                      }}
                      placeholder="例如：6222 0212 3456 7890"
                      data-testid={`card-number-input-${index}`}
                    />
                    {card.cardNumber && !validateCardNumber(card.cardNumber) && (
                      <p className="text-xs text-destructive">银行卡号应为16-19位数字</p>
                    )}
                  </div>

                  <div className="space-y-2">
                    <Label htmlFor={`cardholderName-${index}`}>持卡人姓名 *</Label>
                    <Input
                      id={`cardholderName-${index}`}
                      value={card.cardholderName}
                      onChange={(e) => handleFieldChange(index, 'cardholderName', e.target.value)}
                      placeholder="请输入持卡人姓名"
                      data-testid={`cardholder-name-input-${index}`}
                    />
                  </div>

                  <div className="space-y-2">
                    <Label htmlFor={`cardType-${index}`}>银行卡类型</Label>
                    <Select
                      value={card.cardType || ''}
                      onValueChange={(value) => handleFieldChange(index, 'cardType', value || null)}
                    >
                      <SelectTrigger id={`cardType-${index}`} data-testid={`card-type-select-${index}`}>
                        <SelectValue placeholder="请选择银行卡类型" />
                      </SelectTrigger>
                      <SelectContent>
                        <SelectItem value={BankCardType.FIRST_CLASS}>{BankCardType.FIRST_CLASS}</SelectItem>
                        <SelectItem value={BankCardType.SECOND_CLASS}>{BankCardType.SECOND_CLASS}</SelectItem>
                      </SelectContent>
                    </Select>
                  </div>

                  <div className="space-y-2">
                    <Label>银行卡照片</Label>
                    <FileSelector
                      value={card.fileId}
                      onChange={(fileId) => {
                        console.debug('FileSelector onChange called with:', fileId);
                        handleFileIdChange(index, fileId as number | null);
                      }}
                      accept="image/*"
                      filterType="all"
                      placeholder="选择或上传银行卡照片"
                      data-testid={`bank-card-photo-upload-${index}`}
                    />
                    <p className="text-xs text-muted-foreground">请上传银行卡正面照片</p>
                    {card.fileId && (
                      <p className="text-xs text-green-600">已选择文件ID: {card.fileId}</p>
                    )}
                  </div>

                  <div className="space-y-2 flex items-center">
                    <div className="flex items-center space-x-2">
                      <Switch
                        checked={card.isDefault === 1}
                        onCheckedChange={(checked) => handleFieldChange(index, 'isDefault', checked ? 1 : 0)}
                        data-testid={`default-card-switch-${index}`}
                      />
                      <Label htmlFor={`isDefault-${index}`}>设为默认银行卡</Label>
                    </div>
                    {card.isDefault === 1 && (
                      <p className="text-xs text-muted-foreground">此卡将作为默认收款银行卡</p>
                    )}
                  </div>
                </div>
              </CardContent>
            </Card>
          ))}
        </div>
      )}

      <div className="text-xs text-muted-foreground">
        <p>• 最多可添加 {maxCards} 张银行卡</p>
        <p>• 只能设置一张默认银行卡</p>
        <p>• 银行卡照片用于身份验证</p>
      </div>
    </div>
  );
};

export default BankCardManagement;