import { useState } from 'react';
import { ProTable } from '@ant-design/pro-components';
import type { ProColumns } from '@ant-design/pro-components';
import { Button, Tag, Space, Typography, message } from 'antd';
import {
  CheckCircleOutlined,
  CloseCircleOutlined,
  LoadingOutlined,
  CopyOutlined,
  LinkOutlined,
} from '@ant-design/icons';
import { useChainId } from 'wagmi';
import { getBlockExplorer } from '@/config/contracts';
import type { TransactionRecord } from '@/hooks/useTransactionHistory';

const { Link } = Typography;

interface Props {
  transactions: TransactionRecord[];
  onClear: () => void;
}

export function TransactionHistory({ transactions, onClear }: Props) {
  const [copiedId, setCopiedId] = useState<string | null>(null);
  const chainId = useChainId();
  const blockExplorer = getBlockExplorer(chainId);

  const handleCopy = async (hash: string, txId: string) => {
    try {
      await navigator.clipboard.writeText(hash);
      setCopiedId(txId);
      message.success('已复制');
      setTimeout(() => setCopiedId(null), 1500);
    } catch (err) {
      message.error('复制失败');
    }
  };

  const getTypeLabel = (type: string) => {
    const labels: Record<string, string> = {
      mint: 'Mint USDC',
      burn: 'Burn USDC',
      buy: 'Buy YT',
      sell: 'Sell YT',
      approve: 'Approve',
      create_vault: 'Create Vault',
      update_price: 'Update Price',
      test: 'Test',
      addLiquidity: 'Add Liquidity',
      removeLiquidity: 'Remove Liquidity',
      swap: 'Swap',
      transfer: 'Transfer',
    };
    return labels[type] || type;
  };

  const formatTime = (timestamp: number) => {
    const date = new Date(timestamp);
    return date.toLocaleString();
  };

  const shortenHash = (hash: string | undefined | null) => {
    if (!hash || typeof hash !== 'string' || hash.length < 14) {
      return hash || '-';
    }
    return `${hash.slice(0, 8)}...${hash.slice(-6)}`;
  };

  const columns: ProColumns<TransactionRecord>[] = [
    {
      title: '类型',
      dataIndex: 'type',
      width: 150,
      render: (_, record) => <Tag color="blue">{getTypeLabel(record.type)}</Tag>,
      filters: true,
      onFilter: true,
      valueType: 'select',
      valueEnum: {
        mint: { text: 'Mint USDC' },
        burn: { text: 'Burn USDC' },
        buy: { text: 'Buy YT' },
        sell: { text: 'Sell YT' },
        approve: { text: 'Approve' },
        create_vault: { text: 'Create Vault' },
        update_price: { text: 'Update Price' },
        addLiquidity: { text: 'Add Liquidity' },
        removeLiquidity: { text: 'Remove Liquidity' },
        swap: { text: 'Swap' },
        transfer: { text: 'Transfer' },
      },
    },
    {
      title: '金额',
      dataIndex: 'amount',
      width: 150,
      render: (_, record) =>
        record.amount ? `${record.amount} ${record.token || ''}` : '-',
    },
    {
      title: '状态',
      dataIndex: 'status',
      width: 100,
      render: (_, record) => {
        if (record.status === 'success') {
          return (
            <Tag icon={<CheckCircleOutlined />} color="success">
              成功
            </Tag>
          );
        }
        if (record.status === 'failed') {
          return (
            <Tag icon={<CloseCircleOutlined />} color="error">
              失败
            </Tag>
          );
        }
        return (
          <Tag icon={<LoadingOutlined />} color="processing">
            处理中
          </Tag>
        );
      },
      filters: true,
      onFilter: true,
      valueEnum: {
        success: { text: '成功', status: 'Success' },
        failed: { text: '失败', status: 'Error' },
        pending: { text: '处理中', status: 'Processing' },
      },
    },
    {
      title: '交易哈希',
      dataIndex: 'hash',
      width: 200,
      render: (_, record) => {
        if (record.hash && typeof record.hash === 'string' && record.hash.startsWith('0x')) {
          return (
            <Space>
              <Link
                href={`${blockExplorer}/tx/${record.hash}`}
                target="_blank"
                rel="noopener noreferrer"
              >
                <LinkOutlined /> {shortenHash(record.hash)}
              </Link>
              <Button
                type="text"
                size="small"
                icon={<CopyOutlined />}
                onClick={() => handleCopy(record.hash, record.id)}
              >
                {copiedId === record.id ? '已复制' : ''}
              </Button>
            </Space>
          );
        }
        return <span style={{ color: '#999' }}>-</span>;
      },
    },
    {
      title: '时间',
      dataIndex: 'timestamp',
      width: 180,
      render: (_, record) => formatTime(record.timestamp),
      sorter: (a, b) => a.timestamp - b.timestamp,
      defaultSortOrder: 'descend',
    },
    {
      title: '错误信息',
      dataIndex: 'error',
      ellipsis: true,
      render: (_, record) => {
        if (record.error) {
          return (
            <Typography.Text type="danger" ellipsis={{ tooltip: true }}>
              {typeof record.error === 'string' ? record.error : JSON.stringify(record.error)}
            </Typography.Text>
          );
        }
        return '-';
      },
    },
  ];

  return (
    <ProTable<TransactionRecord>
      columns={columns}
      dataSource={transactions.filter((tx) => tx && tx.id).slice(0, 50)}
      rowKey="id"
      search={false}
      pagination={{
        pageSize: 10,
        showSizeChanger: true,
        showQuickJumper: true,
      }}
      toolBarRender={() => [
        <Button key="clear" danger onClick={onClear}>
          清空历史
        </Button>,
      ]}
      headerTitle="交易历史"
      locale={{
        emptyText: '暂无交易记录',
      }}
    />
  );
}
