import { useState, useEffect, useRef, useMemo } from 'react';
import { useIntl } from '@umijs/max';
import { PageContainer, ProCard, StatisticCard, ProTable } from '@ant-design/pro-components';
import type { ProColumns } from '@ant-design/pro-components';
import {
  Tabs, Input, Button, Space, Typography, Row, Col,
  Alert, message, Progress, Select, Tag, Collapse,
} from 'antd';
import {
  PlusOutlined, MinusOutlined, SwapOutlined, WalletOutlined,
  SettingOutlined, ReloadOutlined, BugOutlined, InfoCircleOutlined, DollarOutlined,
} from '@ant-design/icons';
import {
  useAccount, useReadContract, useWriteContract,
  useWaitForTransactionReceipt,
} from 'wagmi';
import { parseUnits, formatUnits } from 'viem';
import {
  GAS_CONFIG, USDC_ABI, YT_REWARD_ROUTER_ABI,
} from '@/config/contracts';
import { useTransactions } from '@/context/TransactionContext';
import type { TransactionType } from '@/context/TransactionContext';
import { TransactionHistory } from '@/components/TransactionHistory';

import { useLPPoolData } from './useLPPoolData';
import type { ExtendedPoolToken } from './useLPPoolData';
import { useLPAdminActions } from './useLPAdminActions';
import { LPAdminConfig } from './LPAdminConfig';
import { LPBoundaryTest } from './LPBoundaryTest';
import { LPDebugInfo } from './LPDebugInfo';
import { LPUsdyPanel } from './LPUsdyPanel';

const { Text } = Typography;

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

  // ===== 池子数据（链感知）=====
  const poolData = useLPPoolData();
  const {
    chainId, TOKEN_DECIMALS, CONTRACTS,
    poolTokens, allAvailableTokens,
    ytLPBalance, ytLPTotalSupply, ytLPSymbol, ytLPPrice,
    aumInUsdy, cooldownDuration, lastAddedAt,
    emergencyMode, swapEnabled, poolPaused,
    dynamicFees, usdcPriceSource,
    vaultGov, poolManagerGov,
    refetchBalance, refetchTokenBalances, refetchYtLPTotalSupply,
    refetchYtLPPrice, refetchAumInUsdy, refetchPoolAmounts,
  } = poolData;

  const currentChainName = poolData.CONTRACTS ? `Chain ${chainId}` : '';

  // ===== 交易历史 =====
  const { transactions, addTransaction, updateTransaction, clearHistory } = useTransactions();
  const pendingTxRef = useRef<{ id: string; type: TransactionType; amount?: string } | null>(null);

  // ===== 表单状态 =====
  const [activeTab, setActiveTab] = useState('add');
  const [addToken, setAddToken] = useState('');
  const [addAmount, setAddAmount] = useState('');
  const [removeToken, setRemoveToken] = useState('');
  const [removeAmount, setRemoveAmount] = useState('');
  const [swapTokenIn, setSwapTokenIn] = useState('');
  const [swapTokenOut, setSwapTokenOut] = useState('');
  const [swapAmount, setSwapAmount] = useState('');

  // ===== 白名单代币 =====
  const whitelistedTokens = useMemo(() =>
    poolTokens.filter(t => t.isWhitelisted),
    [poolTokens]
  );

  // 初始化默认选中代币
  useEffect(() => {
    if (whitelistedTokens.length > 0) {
      if (!addToken) setAddToken(whitelistedTokens[0].address);
      if (!removeToken) setRemoveToken(whitelistedTokens[0].address);
      if (!swapTokenIn) setSwapTokenIn(whitelistedTokens[0].address);
      if (!swapTokenOut && whitelistedTokens.length > 1) setSwapTokenOut(whitelistedTokens[1].address);
    }
  }, [whitelistedTokens, addToken, removeToken, swapTokenIn, swapTokenOut]);

  // ===== 动态读取授权状态 =====
  const selectedAddToken = poolTokens.find(t => t.address === addToken);
  const selectedSwapTokenIn = poolTokens.find(t => t.address === swapTokenIn);

  const { data: addTokenAllowance, refetch: refetchAddAllowance } = useReadContract({
    address: addToken as `0x${string}`,
    abi: USDC_ABI,
    functionName: 'allowance',
    args: address && addToken ? [address, CONTRACTS.YT_REWARD_ROUTER] : undefined,
  });

  const { data: ytLPAllowance, refetch: refetchYtLPAllowance } = useReadContract({
    address: CONTRACTS.YT_LP_TOKEN as `0x${string}`,
    abi: USDC_ABI,
    functionName: 'allowance',
    args: address ? [address, CONTRACTS.YT_REWARD_ROUTER] : undefined,
  });

  const { data: swapTokenAllowance, refetch: refetchSwapAllowance } = useReadContract({
    address: swapTokenIn as `0x${string}`,
    abi: USDC_ABI,
    functionName: 'allowance',
    args: address && swapTokenIn ? [address, CONTRACTS.YT_REWARD_ROUTER] : undefined,
  });

  // ===== 交易处理 =====
  const { writeContract, data: hash, isPending, reset, error: writeError } = useWriteContract();
  const { isLoading: isConfirming, isSuccess, isError, error: txError } = useWaitForTransactionReceipt({ hash });

  useEffect(() => {
    if (hash && typeof hash === 'string' && hash.startsWith('0x') && pendingTxRef.current) {
      updateTransaction(pendingTxRef.current.id, { hash, status: 'pending' });
      message.info('交易已提交');
    }
  }, [hash]);

  useEffect(() => {
    if (isSuccess) {
      if (pendingTxRef.current) {
        updateTransaction(pendingTxRef.current.id, { status: 'success' });
        message.success('交易成功');
        pendingTxRef.current = null;
      }
      refetchBalance();
      refetchTokenBalances();
      refetchPoolAmounts();
      refetchYtLPTotalSupply();
      refetchAumInUsdy();
      refetchYtLPPrice();
      refetchAddAllowance();
      refetchYtLPAllowance();
      refetchSwapAllowance();
      setAddAmount('');
      setRemoveAmount('');
      setSwapAmount('');
    }
  }, [isSuccess]);

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

  useEffect(() => {
    if (writeError) {
      const errorMsg = typeof writeError === 'string' ? writeError : writeError.message || '操作失败';
      message.error(errorMsg.slice(0, 120));
      if (pendingTxRef.current) {
        updateTransaction(pendingTxRef.current.id, { status: 'failed', error: errorMsg });
        pendingTxRef.current = null;
      }
      reset();
    }
  }, [writeError]);

  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;

  // ===== 管理员操作 =====
  const adminActions = useLPAdminActions({
    address,
    writeContract,
    recordTx: recordTx as (type: string, amount?: string, token?: string) => void,
  });

  // ===== 操作函数 =====
  const handleApprove = (tokenAddress: string, spender: string, tokenSymbol: string, amount: string, decimals: number) => {
    if (!amount) return;
    recordTx('approve', amount, tokenSymbol);
    writeContract({
      address: tokenAddress as `0x${string}`,
      abi: USDC_ABI,
      functionName: 'approve',
      args: [spender as `0x${string}`, parseUnits(amount, decimals)],
      gas: GAS_CONFIG.SIMPLE,
    });
  };

  const handleAddLiquidity = () => {
    if (!addAmount || !addToken) return;
    const token = poolTokens.find(t => t.address === addToken);
    recordTx('addLiquidity', addAmount, token?.symbol || 'Token');
    writeContract({
      address: CONTRACTS.YT_REWARD_ROUTER,
      abi: YT_REWARD_ROUTER_ABI,
      functionName: 'addLiquidity',
      args: [addToken as `0x${string}`, parseUnits(addAmount, token?.decimals || 18), 0n, 0n],
      gas: GAS_CONFIG.COMPLEX,
    });
  };

  const handleRemoveLiquidity = () => {
    if (!removeAmount || !removeToken) return;
    const token = poolTokens.find(t => t.address === removeToken);
    recordTx('removeLiquidity', removeAmount, token?.symbol || 'Token');
    writeContract({
      address: CONTRACTS.YT_REWARD_ROUTER,
      abi: YT_REWARD_ROUTER_ABI,
      functionName: 'removeLiquidity',
      args: [removeToken as `0x${string}`, parseUnits(removeAmount, TOKEN_DECIMALS.YT), 0n, address as `0x${string}`],
      gas: GAS_CONFIG.COMPLEX,
    });
  };

  const handleSwap = () => {
    if (!swapAmount || !swapTokenIn || !swapTokenOut) return;
    const tokenIn = poolTokens.find(t => t.address === swapTokenIn);
    const tokenOut = poolTokens.find(t => t.address === swapTokenOut);
    recordTx('swap', swapAmount, `${tokenIn?.symbol} → ${tokenOut?.symbol}`);
    writeContract({
      address: CONTRACTS.YT_REWARD_ROUTER,
      abi: YT_REWARD_ROUTER_ABI,
      functionName: 'swap',
      args: [
        swapTokenIn as `0x${string}`,
        swapTokenOut as `0x${string}`,
        parseUnits(swapAmount, tokenIn?.decimals || 18),
        0n,
        address as `0x${string}`,
      ],
      gas: GAS_CONFIG.COMPLEX,
    });
  };

  // ===== 工具函数 =====
  const formatBalance = (balance: bigint | undefined, decimals: number = TOKEN_DECIMALS.USDC) => {
    if (!balance) return '0.00';
    return Number(formatUnits(balance, decimals)).toLocaleString(undefined, {
      minimumFractionDigits: 2, maximumFractionDigits: 6,
    });
  };

  const cooldownRemaining = () => {
    if (!lastAddedAt || !cooldownDuration) return 0;
    const now = Math.floor(Date.now() / 1000);
    const elapsed = now - Number(lastAddedAt);
    return Math.max(0, Number(cooldownDuration) - elapsed);
  };
  const canRemove = cooldownRemaining() === 0;

  const totalWeight = poolTokens.reduce((sum, t) => sum + (t.weight || 0n), 0n);
  const totalUsdy = poolTokens.reduce((sum, t) => sum + (t.usdyAmount || 0n), 0n);

  // ===== 授权判断 =====
  const needsAddApproval = !addTokenAllowance || addTokenAllowance < parseUnits(addAmount || '0', selectedAddToken?.decimals || 18);
  const needsRemoveApproval = !ytLPAllowance || ytLPAllowance < parseUnits(removeAmount || '0', TOKEN_DECIMALS.YT);
  const needsSwapApproval = !swapTokenAllowance || swapTokenAllowance < parseUnits(swapAmount || '0', selectedSwapTokenIn?.decimals || 18);

  // ===== ProTable 列定义 =====
  const tokenColumns: ProColumns<ExtendedPoolToken>[] = [
    {
      title: '代币', dataIndex: 'symbol', width: 90, fixed: 'left',
      render: (_, record) => (
        <span>
          <Text strong>{record.symbol}</Text>
          {record.isStable && <Tag color="blue" style={{ marginLeft: 4, fontSize: 10 }}>稳定</Tag>}
        </span>
      ),
    },
    {
      title: '白名单', dataIndex: 'isWhitelisted', width: 70,
      render: (_, record) => record.isWhitelisted ? <Tag color="green">✓</Tag> : <Tag color="red">✗</Tag>,
    },
    // ===== 用户层面（根据当前地址查询）=====
    {
      title: '钱包余额', dataIndex: 'balance', width: 120,
      render: (_, record) => formatBalance(record.balance, record.decimals),
    },
    {
      title: '钱包USDY价值', dataIndex: 'usdyValue', width: 130,
      render: (_, record) => formatBalance(record.usdyValue, TOKEN_DECIMALS.USDY),
    },
    // ===== 合约层面 =====
    {
      title: '池内数量', dataIndex: 'poolAmount', width: 120,
      render: (_, record) => formatBalance(record.poolAmount, record.decimals),
    },
    {
      title: '池内USDY', dataIndex: 'usdyAmount', width: 120,
      render: (_, record) => formatBalance(record.usdyAmount, TOKEN_DECIMALS.USDY),
    },
    {
      title: '权重', dataIndex: 'weight', width: 70,
      render: (_, record) => record.weight?.toString() || '0',
    },
    {
      title: '目标比例', width: 90,
      render: (_, record) => {
        const ratio = totalWeight > 0n ? (Number(record.weight || 0n) / Number(totalWeight)) * 100 : 0;
        return `${ratio.toFixed(1)}%`;
      },
    },
    {
      title: '当前比例', width: 90,
      render: (_, record) => {
        const ratio = totalUsdy > 0n ? (Number(record.usdyAmount || 0n) / Number(totalUsdy)) * 100 : 0;
        return `${ratio.toFixed(1)}%`;
      },
    },
    {
      title: '偏差', width: 80,
      render: (_, record) => {
        const target = totalWeight > 0n ? (Number(record.weight || 0n) / Number(totalWeight)) * 100 : 0;
        const current = totalUsdy > 0n ? (Number(record.usdyAmount || 0n) / Number(totalUsdy)) * 100 : 0;
        const deviation = current - target;
        return (
          <Text style={{
            color: Math.abs(deviation) < 1 ? '#52c41a' : Math.abs(deviation) < 5 ? '#faad14' : '#f5222d',
            fontWeight: Math.abs(deviation) >= 5 ? 'bold' : 'normal',
          }}>
            {deviation >= 0 ? '+' : ''}{deviation.toFixed(1)}%
          </Text>
        );
      },
    },
  ];

  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>
    );
  }

  return (
    <PageContainer
      title={`${intl.formatMessage({ id: 'pages.lp.title' })} (Chain ${chainId})`}
      extra={[
        <Button key="refresh" icon={<ReloadOutlined />} onClick={() => {
          refetchBalance(); refetchTokenBalances(); refetchPoolAmounts(); refetchAumInUsdy(); refetchYtLPPrice();
        }}>刷新</Button>,
      ]}
    >
      <Space direction="vertical" size="large" style={{ width: '100%' }}>

        {/* 状态提示 */}
        {poolPaused && <Alert message="池子已暂停" type="error" showIcon />}
        {emergencyMode && <Alert message="紧急模式 - 仅允许移除流动性" type="error" showIcon />}
        {!swapEnabled && !emergencyMode && <Alert message="Swap 功能已禁用" type="warning" showIcon />}

        {/* 池子信息统计 */}
        <Row gutter={[16, 16]}>
          <Col xs={24} sm={12} md={6}>
            <StatisticCard statistic={{
              title: intl.formatMessage({ id: 'pages.lp.yourLiquidity' }),
              value: formatBalance(ytLPBalance as bigint, TOKEN_DECIMALS.YT),
              suffix: ytLPSymbol as string || 'ytLP',
            }} />
          </Col>
          <Col xs={24} sm={12} md={6}>
            <StatisticCard statistic={{
              title: `${ytLPSymbol || 'ytLP'} 总供应`,
              value: formatBalance(ytLPTotalSupply as bigint, TOKEN_DECIMALS.YT),
            }} />
          </Col>
          <Col xs={24} sm={12} md={6}>
            <StatisticCard statistic={{
              title: 'LP 价格',
              value: formatBalance(ytLPPrice as bigint, TOKEN_DECIMALS.USDY),
              suffix: 'USDY',
            }} />
          </Col>
          <Col xs={24} sm={12} md={6}>
            <StatisticCard
              style={{ background: 'linear-gradient(135deg, #667eea 0%, #764ba2 100%)' }}
              statistic={{
                title: <span style={{ color: 'rgba(255,255,255,0.9)' }}>AUM (USDY)</span>,
                value: formatBalance(aumInUsdy as bigint, TOKEN_DECIMALS.USDY),
                valueStyle: { color: 'white' },
              }}
            />
          </Col>
        </Row>

        {/* 代币余额表格 */}
        <ProCard title="代币余额表">
          <ProTable<ExtendedPoolToken>
            columns={tokenColumns}
            dataSource={poolTokens}
            rowKey="address"
            search={false}
            pagination={false}
            options={false}
            size="small"
          />
          <Text type="secondary" style={{ fontSize: 12, marginTop: 8, display: 'block' }}>
            偏差: 正值表示该代币过多（卖出费率高），负值表示不足（买入费率低）
          </Text>
        </ProCard>

        {/* 操作面板 */}
        <ProCard>
          <Tabs
            activeKey={activeTab}
            onChange={setActiveTab}
            items={[
              {
                key: 'add',
                label: <span><PlusOutlined /> {intl.formatMessage({ id: 'pages.lp.addLiquidity' })}</span>,
                children: (
                  <Space direction="vertical" size="middle" style={{ width: '100%' }}>
                    <div>
                      <Text strong>选择代币</Text>
                      <Select
                        size="large" style={{ width: '100%', marginTop: 8 }}
                        value={addToken} onChange={setAddToken}
                        options={whitelistedTokens.map(t => ({
                          label: `${t.symbol} (余额: ${formatBalance(t.balance, t.decimals)})`,
                          value: t.address,
                        }))}
                      />
                    </div>
                    <div>
                      <Text strong>数量</Text>
                      <Input
                        size="large" type="number" value={addAmount}
                        onChange={e => setAddAmount(e.target.value)}
                        placeholder={intl.formatMessage({ id: 'pages.vault.enterAmount' })}
                        style={{ marginTop: 8 }}
                      />
                    </div>
                    {needsAddApproval ? (
                      <Button type="primary" size="large" block loading={isProcessing}
                        onClick={() => handleApprove(addToken, CONTRACTS.YT_REWARD_ROUTER, selectedAddToken?.symbol || 'Token', addAmount, selectedAddToken?.decimals || 18)}>
                        {intl.formatMessage({ id: 'pages.vault.approve' })} {selectedAddToken?.symbol}
                      </Button>
                    ) : (
                      <Button type="primary" size="large" icon={<PlusOutlined />} block
                        onClick={handleAddLiquidity} loading={isProcessing}
                        disabled={!addAmount || isProcessing}>
                        {intl.formatMessage({ id: 'pages.lp.addLiquidity' })}
                      </Button>
                    )}
                  </Space>
                ),
              },
              {
                key: 'remove',
                label: <span><MinusOutlined /> {intl.formatMessage({ id: 'pages.lp.removeLiquidity' })}</span>,
                children: (
                  <Space direction="vertical" size="middle" style={{ width: '100%' }}>
                    {!canRemove && (
                      <Alert
                        message="冷却期中"
                        description={
                          <div>
                            <p>剩余时间: {cooldownRemaining()} 秒</p>
                            <Progress
                              percent={Math.floor((1 - cooldownRemaining() / Number(cooldownDuration || 1)) * 100)}
                              status="active"
                            />
                          </div>
                        }
                        type="warning"
                      />
                    )}
                    <div>
                      <Text strong>选择代币</Text>
                      <Select
                        size="large" style={{ width: '100%', marginTop: 8 }}
                        value={removeToken} onChange={setRemoveToken}
                        options={whitelistedTokens.map(t => ({ label: t.symbol, value: t.address }))}
                      />
                    </div>
                    <div>
                      <Text strong>ytLP 数量</Text>
                      <Input
                        size="large" type="number" value={removeAmount}
                        onChange={e => setRemoveAmount(e.target.value)}
                        placeholder={intl.formatMessage({ id: 'pages.vault.enterAmount' })}
                        suffix={<Text type="secondary">余额: {formatBalance(ytLPBalance as bigint, TOKEN_DECIMALS.YT)}</Text>}
                        style={{ marginTop: 8 }}
                      />
                    </div>
                    {needsRemoveApproval ? (
                      <Button type="primary" size="large" block loading={isProcessing}
                        onClick={() => handleApprove(CONTRACTS.YT_LP_TOKEN, CONTRACTS.YT_REWARD_ROUTER, ytLPSymbol as string || 'ytLP', removeAmount, 18)}>
                        {intl.formatMessage({ id: 'pages.vault.approve' })} {ytLPSymbol}
                      </Button>
                    ) : (
                      <Button type="primary" danger size="large" icon={<MinusOutlined />} block
                        onClick={handleRemoveLiquidity} loading={isProcessing}
                        disabled={!removeAmount || isProcessing || !canRemove}>
                        {intl.formatMessage({ id: 'pages.lp.removeLiquidity' })}
                      </Button>
                    )}
                  </Space>
                ),
              },
              {
                key: 'swap',
                label: <span><SwapOutlined /> Token Swap</span>,
                disabled: !swapEnabled || !!emergencyMode,
                children: (
                  <Space direction="vertical" size="middle" style={{ width: '100%' }}>
                    <div>
                      <Text strong>从 (TokenIn)</Text>
                      <Select
                        size="large" style={{ width: '100%', marginTop: 8 }}
                        value={swapTokenIn} onChange={setSwapTokenIn}
                        options={whitelistedTokens.map(t => ({
                          label: `${t.symbol} (余额: ${formatBalance(t.balance, t.decimals)})`,
                          value: t.address,
                        }))}
                      />
                    </div>
                    <div>
                      <Text strong>到 (TokenOut)</Text>
                      <Select
                        size="large" style={{ width: '100%', marginTop: 8 }}
                        value={swapTokenOut} onChange={setSwapTokenOut}
                        options={whitelistedTokens.filter(t => t.address !== swapTokenIn).map(t => ({
                          label: t.symbol, value: t.address,
                        }))}
                      />
                    </div>
                    <div>
                      <Text strong>数量</Text>
                      <Input
                        size="large" type="number" value={swapAmount}
                        onChange={e => setSwapAmount(e.target.value)}
                        placeholder={intl.formatMessage({ id: 'pages.vault.enterAmount' })}
                        style={{ marginTop: 8 }}
                      />
                    </div>
                    {needsSwapApproval ? (
                      <Button type="primary" size="large" block loading={isProcessing}
                        onClick={() => handleApprove(swapTokenIn, CONTRACTS.YT_REWARD_ROUTER, selectedSwapTokenIn?.symbol || 'Token', swapAmount, selectedSwapTokenIn?.decimals || 18)}>
                        {intl.formatMessage({ id: 'pages.vault.approve' })} {selectedSwapTokenIn?.symbol}
                      </Button>
                    ) : (
                      <Button type="primary" size="large" icon={<SwapOutlined />} block
                        onClick={handleSwap} loading={isProcessing}
                        disabled={!swapAmount || isProcessing || swapTokenIn === swapTokenOut}>
                        Swap
                      </Button>
                    )}
                  </Space>
                ),
              },
            ]}
          />
        </ProCard>

        {/* 管理员配置 + 扩展面板 */}
        <Collapse
          style={{ background: '#fff' }}
          items={[
            {
              key: 'admin',
              label: <span style={{ cursor: 'pointer' }}><SettingOutlined /> 管理员配置</span>,
              children: (
                <LPAdminConfig
                  address={address}
                  isProcessing={isProcessing}
                  poolPaused={poolPaused as boolean}
                  dynamicFees={dynamicFees as boolean}
                  emergencyMode={emergencyMode as boolean}
                  swapEnabled={swapEnabled as boolean}
                  cooldownDuration={cooldownDuration as bigint}
                  usdcPriceSource={usdcPriceSource as string}
                  availableTokens={allAvailableTokens}
                  show={true}
                  onToggle={() => {}}
                  handleSetCooldownDuration={adminActions.handleSetCooldownDuration}
                  handleSetSwapFees={adminActions.handleSetSwapFees}
                  handleWithdrawToken={adminActions.handleWithdrawToken}
                  handleSetDynamicFees={adminActions.handleSetDynamicFees}
                  handlePausePool={adminActions.handlePausePool}
                  handleUnpausePool={adminActions.handleUnpausePool}
                  handleSetMaxSwapAmount={adminActions.handleSetMaxSwapAmount}
                  handleSetAumAdjustment={adminActions.handleSetAumAdjustment}
                  handleSetMaxSwapSlippageBps={adminActions.handleSetMaxSwapSlippageBps}
                  handleSetMaxPriceChangeBps={adminActions.handleSetMaxPriceChangeBps}
                  handleSetPoolManagerGov={adminActions.handleSetPoolManagerGov}
                  handleSetVaultGov={adminActions.handleSetVaultGov}
                  handleSetHandler={adminActions.handleSetHandler}
                  handleSetKeeper={adminActions.handleSetKeeper}
                  handleSetSwapper={adminActions.handleSetSwapper}
                  handleSetPoolManager={adminActions.handleSetPoolManager}
                  handleSetMinter={adminActions.handleSetMinter}
                  handleSetWhitelistedToken={adminActions.handleSetWhitelistedToken}
                  handleClearWhitelistedToken={adminActions.handleClearWhitelistedToken}
                  handleSetEmergencyMode={adminActions.handleSetEmergencyMode}
                  handleSetSwapEnabled={adminActions.handleSetSwapEnabled}
                  handleSetPrice={adminActions.handleSetPrice}
                  handleSetSpread={adminActions.handleSetSpread}
                  handleSetUsdcPriceSource={adminActions.handleSetUsdcPriceSource}
                  handleSetStableToken={adminActions.handleSetStableToken}
                  handleAddUsdyVault={adminActions.handleAddUsdyVault}
                  handleRemoveUsdyVault={adminActions.handleRemoveUsdyVault}
                />
              ),
            },
            {
              key: 'boundary',
              label: <span style={{ cursor: 'pointer' }}><BugOutlined /> 边界测试</span>,
              children: (
                <LPBoundaryTest
                  address={address}
                  ytLPBalance={ytLPBalance as bigint}
                  isProcessing={isProcessing}
                  writeContract={writeContract}
                  recordTx={recordTx}
                  show={true}
                  onToggle={() => {}}
                  rewardRouter={CONTRACTS?.YT_REWARD_ROUTER}
                  vaultAddresses={poolTokens.map(t => t.address)}
                  ytDecimals={TOKEN_DECIMALS.YT}
                  ytLpDecimals={TOKEN_DECIMALS.YT_LP}
                />
              ),
            },
            {
              key: 'usdy',
              label: <span style={{ cursor: 'pointer' }}><DollarOutlined /> USDY 操作</span>,
              children: (
                <LPUsdyPanel
                  show={true}
                  onToggle={() => {}}
                />
              ),
            },
            {
              key: 'debug',
              label: <span style={{ cursor: 'pointer' }}><InfoCircleOutlined /> 调试信息</span>,
              children: (
                <LPDebugInfo
                  vaultGov={vaultGov as string}
                  poolManagerGov={poolManagerGov as string}
                  show={true}
                  onToggle={() => {}}
                />
              ),
            },
          ]}
        />

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