import { useState, useEffect, useRef } from 'react';
import { useIntl } from '@umijs/max';
import { PageContainer, ProCard, StatisticCard } from '@ant-design/pro-components';
import { Input, Button, Space, Typography, Divider, message, Row, Col } from 'antd';
import { SendOutlined, WalletOutlined } from '@ant-design/icons';
import { useAccount, useReadContract, useWriteContract, useWaitForTransactionReceipt, useChainId } from 'wagmi';
import { parseUnits, formatUnits } from 'viem';
import { GAS_CONFIG, USDC_ABI, getContracts, getDecimals, getChainName } from '@/config/contracts';
import { useTransactions } from '@/context/TransactionContext';
import type { TransactionType } from '@/context/TransactionContext';
import { TransactionHistory } from '@/components/TransactionHistory';

const { Text, Title } = Typography;
const { Statistic } = StatisticCard;

export default function USDCPage() {
  const intl = useIntl();
  const { address, isConnected } = useAccount();

  // 多链支持
  const chainId = useChainId();
  const CONTRACTS = getContracts(chainId);
  const TOKEN_DECIMALS = getDecimals(chainId);
  const currentChainName = getChainName(chainId);

  const { transactions, addTransaction, updateTransaction, clearHistory } = useTransactions();
  const [transferTo, setTransferTo] = useState('');
  const [transferAmount, setTransferAmount] = useState('');
  const pendingTxRef = useRef<{ id: string; type: TransactionType; amount?: string } | null>(null);

  // 读取合约数据
  const { data: balance, refetch: refetchBalance } = useReadContract({
    address: CONTRACTS.USDC,
    abi: USDC_ABI,
    functionName: 'balanceOf',
    args: address ? [address] : undefined,
  });

  const { data: symbol } = useReadContract({
    address: CONTRACTS.USDC,
    abi: USDC_ABI,
    functionName: 'symbol',
  });

  const { data: decimals } = useReadContract({
    address: CONTRACTS.USDC,
    abi: USDC_ABI,
    functionName: 'decimals',
  });

  const { data: totalSupply, refetch: refetchTotalSupply } = useReadContract({
    address: CONTRACTS.USDC,
    abi: USDC_ABI,
    functionName: 'totalSupply',
  });

  const { data: name } = useReadContract({
    address: CONTRACTS.USDC,
    abi: USDC_ABI,
    functionName: 'name',
  });

  // 写入合约
  const { writeContract, data: hash, isPending, error: writeError, reset, status: writeStatus } = useWriteContract();

  const { isLoading: isConfirming, isSuccess, isError, error: txError } = useWaitForTransactionReceipt({
    hash,
  });

  // 超时自动重置机制
  useEffect(() => {
    let timeoutId: NodeJS.Timeout | null = null;
    if (isPending && !hash) {
      timeoutId = setTimeout(() => {
        console.log('Transaction timeout, resetting state...');
        if (pendingTxRef.current) {
          updateTransaction(pendingTxRef.current.id, { status: 'failed', error: 'Transaction timeout' });
          pendingTxRef.current = null;
        }
        message.error(intl.formatMessage({ id: 'pages.toast.txTimeout' }));
        reset();
      }, 30000);
    }
    return () => {
      if (timeoutId) clearTimeout(timeoutId);
    };
  }, [isPending, hash]);

  // 处理交易提交
  useEffect(() => {
    if (hash && typeof hash === 'string' && hash.startsWith('0x') && pendingTxRef.current) {
      updateTransaction(pendingTxRef.current.id, { hash, status: 'pending' });
      message.info(intl.formatMessage({ id: 'pages.toast.txSubmitted' }));
    }
  }, [hash]);

  // 处理交易成功
  useEffect(() => {
    if (isSuccess) {
      if (pendingTxRef.current) {
        updateTransaction(pendingTxRef.current.id, { status: 'success' });
        message.success(intl.formatMessage({ id: 'pages.toast.txSuccess' }));
        pendingTxRef.current = null;
      }
      refetchBalance();
      refetchTotalSupply();
      setTransferTo('');
      setTransferAmount('');
    }
  }, [isSuccess]);

  // 处理交易失败
  useEffect(() => {
    if (isError && pendingTxRef.current) {
      const errMsg = typeof txError?.message === 'string' ? txError.message : 'Transaction failed';
      updateTransaction(pendingTxRef.current.id, {
        status: 'failed',
        error: errMsg
      });
      message.error(intl.formatMessage({ id: 'pages.toast.txFailed' }));
      pendingTxRef.current = null;
      reset();
    }
  }, [isError]);

  // 处理写入错误
  useEffect(() => {
    if (writeError) {
      const errorMsg = parseError(writeError);
      message.error(errorMsg);
      if (pendingTxRef.current) {
        updateTransaction(pendingTxRef.current.id, { status: 'failed', error: errorMsg });
        pendingTxRef.current = null;
      }
      reset();
    }
  }, [writeError]);

  const parseError = (error: any): string => {
    let msg = 'Unknown error';
    if (typeof error === 'string') {
      msg = error;
    } else if (error?.shortMessage) {
      msg = error.shortMessage;
    } else if (typeof error?.message === 'string') {
      msg = error.message;
    } else if (error?.message) {
      msg = JSON.stringify(error.message);
    } else if (error) {
      try { msg = JSON.stringify(error) } catch { msg = String(error) }
    }

    if (msg.includes('User rejected') || msg.includes('user rejected')) {
      return intl.formatMessage({ id: 'pages.toast.userRejected' });
    }
    if (msg.includes('insufficient funds') || msg.includes('InsufficientBalance') || msg.includes('less than block base fee')) {
      return intl.formatMessage({ id: 'pages.toast.insufficientBalance' }) + ' (Gas)';
    }
    const match = msg.match(/error[:\s]+(\w+)/i);
    if (match) return match[1];
    return msg.slice(0, 100);
  };

  const recordTx = (type: TransactionType, amount?: string, token?: string) => {
    const id = addTransaction({
      type,
      hash: '',
      status: 'pending',
      amount,
      token,
    });
    pendingTxRef.current = { id, type, amount };
  };

  // 计算按钮是否应该禁用
  const isProcessing = (isPending || isConfirming) && writeStatus !== 'error';

  const handleTransfer = async () => {
    const tokenDecimals = decimals ?? TOKEN_DECIMALS.USDC;
    if (!address || !transferTo || !transferAmount) return;

    // 验证地址格式
    if (!transferTo.startsWith('0x') || transferTo.length !== 42) {
      message.error(intl.formatMessage({ id: 'pages.usdc.invalidAddress' }));
      return;
    }

    recordTx('transfer', transferAmount, 'USDC');
    writeContract({
      address: CONTRACTS.USDC,
      abi: USDC_ABI,
      functionName: 'transfer',
      args: [transferTo as `0x${string}`, parseUnits(transferAmount, tokenDecimals)],
      gas: GAS_CONFIG.STANDARD,
    });
  };

  if (!isConnected) {
    return (
      <PageContainer>
        <ProCard>
          <Space direction="vertical" size="large" style={{ width: '100%', textAlign: 'center', padding: '40px 0' }}>
            <WalletOutlined style={{ fontSize: 64, color: '#bbb' }} />
            <Text type="secondary">{intl.formatMessage({ id: 'pages.common.connectFirst' })}</Text>
          </Space>
        </ProCard>
      </PageContainer>
    );
  }

  const tokenDecimals = decimals ?? TOKEN_DECIMALS.USDC;
  const balanceValue = balance !== undefined
    ? Number(formatUnits(balance, tokenDecimals))
    : 0;
  const totalSupplyValue = totalSupply !== undefined
    ? Number(formatUnits(totalSupply, tokenDecimals))
    : 0;

  return (
    <PageContainer
      title={`${intl.formatMessage({ id: 'pages.usdc.title' })} (${currentChainName})`}
    >
      <Space direction="vertical" size="large" style={{ width: '100%' }}>

        {/* 代币信息卡片 */}
        <Row gutter={[16, 16]}>
          <Col xs={24} sm={12} md={6}>
            <StatisticCard
              statistic={{
                title: intl.formatMessage({ id: 'pages.usdc.tokenName' }),
                value: name || 'USD Coin',
              }}
            />
          </Col>
          <Col xs={24} sm={12} md={6}>
            <StatisticCard
              statistic={{
                title: intl.formatMessage({ id: 'pages.usdc.tokenSymbol' }),
                value: symbol || 'USDC',
              }}
            />
          </Col>
          <Col xs={24} sm={12} md={6}>
            <StatisticCard
              statistic={{
                title: intl.formatMessage({ id: 'pages.usdc.decimals' }),
                value: tokenDecimals.toString(),
              }}
            />
          </Col>
          <Col xs={24} sm={12} md={6}>
            <StatisticCard
              statistic={{
                title: intl.formatMessage({ id: 'pages.usdc.totalSupply' }),
                value: totalSupplyValue,
                precision: 0,
              }}
            />
          </Col>
        </Row>

        {/* 合约地址 */}
        <ProCard title={intl.formatMessage({ id: 'pages.common.contract' })} size="small">
          <Text code copyable style={{ wordBreak: 'break-all' }}>
            {CONTRACTS.USDC}
          </Text>
        </ProCard>

        {/* 用户余额 */}
        <StatisticCard
          style={{
            background: 'linear-gradient(135deg, #2775ca 0%, #1e5aa8 100%)',
          }}
          statistic={{
            title: <span style={{ color: 'rgba(255,255,255,0.9)' }}>{intl.formatMessage({ id: 'pages.common.balance' })}</span>,
            value: balanceValue,
            precision: 6,
            suffix: <span style={{ color: 'white' }}>{symbol || 'USDC'}</span>,
            valueStyle: { color: 'white', fontSize: 32 },
          }}
        />

        {/* 提示信息 */}
        <ProCard type="inner" size="small">
          <Text type="secondary">
            <strong>{intl.formatMessage({ id: 'pages.usdc.tip' })}</strong>
          </Text>
        </ProCard>

        {/* 转账功能 */}
        <ProCard title={intl.formatMessage({ id: 'pages.usdc.transfer' })}>
          <Space direction="vertical" size="middle" style={{ width: '100%' }}>
            <div>
              <Text strong>{intl.formatMessage({ id: 'pages.usdc.toAddress' })}</Text>
              <Input
                size="large"
                value={transferTo}
                onChange={(e) => setTransferTo(e.target.value)}
                placeholder="0x..."
                style={{ marginTop: 8 }}
              />
            </div>
            <div>
              <Text strong>{intl.formatMessage({ id: 'pages.usdc.transferAmount' })}</Text>
              <Input
                size="large"
                type="number"
                value={transferAmount}
                onChange={(e) => setTransferAmount(e.target.value)}
                placeholder={intl.formatMessage({ id: 'pages.usdc.enterAmount' })}
                style={{ marginTop: 8 }}
              />
            </div>
            <Button
              type="primary"
              size="large"
              icon={<SendOutlined />}
              onClick={handleTransfer}
              disabled={isProcessing || !transferTo || !transferAmount}
              loading={isProcessing}
              block
            >
              {isProcessing ? intl.formatMessage({ id: 'pages.toast.txSubmitted' }) : intl.formatMessage({ id: 'pages.usdc.transfer' })}
            </Button>
          </Space>
        </ProCard>

        {/* 交易历史 */}
        <TransactionHistory transactions={transactions} onClear={clearHistory} />
      </Space>
    </PageContainer>
  );
}
