/**
 * LP 操作组件
 * 包含添加流动性、移除流动性、代币交换功能
 */

import { useState, useMemo, useEffect, useRef } from 'react'
import { Button, InputNumber, Select, Tabs, Row, Col, Alert, Space, Typography } from 'antd'
import { useIntl } from '@umijs/max'
import { parseUnits, formatUnits } from 'viem'
import { useReadContract, useChainId } from 'wagmi'
import {
  CONTRACTS,
  GAS_CONFIG,
  TOKEN_DECIMALS,
  getTokenDecimals,
  getDecimals,
  YT_REWARD_ROUTER_ABI,
  YT_VAULT_ABI,
  USDC_ABI,
  YT_POOL_MANAGER_ABI,
} from '@/config/contracts'
import type { TransactionType } from '@/context/TransactionContext'
import type { ExtendedPoolToken } from './useLPPoolData'
import type { AddLiquidityForm, RemoveLiquidityForm, SwapForm } from './types'

const { Text } = Typography

interface LPOperationsProps {
  address: `0x${string}` | undefined
  poolTokens: ExtendedPoolToken[]
  ytLPBalance?: bigint
  ytLPPrice?: bigint
  isProcessing: boolean
  writeContract: (config: any) => void
  recordTx: (type: TransactionType, amount?: string, token?: string) => void
  getTokenSymbol: (address: string) => string
  // 手续费信息
  swapFee?: bigint
  taxBasisPoints?: bigint
  dynamicFees?: boolean
}

export function LPOperations({
  address,
  poolTokens,
  ytLPBalance,
  ytLPPrice,
  isProcessing,
  writeContract,
  recordTx,
  getTokenSymbol,
  swapFee,
  taxBasisPoints,
  dynamicFees,
}: LPOperationsProps) {
  const { formatMessage } = useIntl()
  const t = (id: string) => formatMessage({ id })

  // ===== 多链支持 =====
  const chainId = useChainId()
  const TOKEN_DECIMALS_DYNAMIC = getDecimals(chainId)

  // Tab 状态
  const [activeTab, setActiveTab] = useState<'add' | 'remove' | 'swap'>('add')

  // 表单状态
  const [addLiquidityForm, setAddLiquidityForm] = useState<AddLiquidityForm>({
    token: poolTokens.find(t => t.isWhitelisted)?.address || '',
    amount: '',
    slippage: '0.5',
  })

  const [removeLiquidityForm, setRemoveLiquidityForm] = useState<RemoveLiquidityForm>({
    token: poolTokens.find(t => t.isWhitelisted)?.address || '',
    amount: '',
    slippage: '1',
  })

  const [swapForm, setSwapForm] = useState<SwapForm>({
    tokenIn: poolTokens.find(t => t.isWhitelisted)?.address || '',
    tokenOut: poolTokens.filter(t => t.isWhitelisted)[1]?.address || '',
    amount: '',
    slippage: '0.5',
  })

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

  // 当 poolTokens 加载完成后，自动设置默认代币
  useEffect(() => {
    if (whitelistedTokens.length > 0) {
      if (!addLiquidityForm.token || !whitelistedTokens.find(t => t.address === addLiquidityForm.token)) {
        setAddLiquidityForm(prev => ({ ...prev, token: whitelistedTokens[0].address }))
      }
      if (!removeLiquidityForm.token || !whitelistedTokens.find(t => t.address === removeLiquidityForm.token)) {
        setRemoveLiquidityForm(prev => ({ ...prev, token: whitelistedTokens[0].address }))
      }
      if (!swapForm.tokenIn || !whitelistedTokens.find(t => t.address === swapForm.tokenIn)) {
        setSwapForm(prev => ({ ...prev, tokenIn: whitelistedTokens[0].address }))
      }
      if (!swapForm.tokenOut || !whitelistedTokens.find(t => t.address === swapForm.tokenOut)) {
        const secondToken = whitelistedTokens[1]?.address || whitelistedTokens[0]?.address || ''
        setSwapForm(prev => ({ ...prev, tokenOut: secondToken }))
      }
    }
  }, [whitelistedTokens, addLiquidityForm.token, removeLiquidityForm.token, swapForm.tokenIn, swapForm.tokenOut])

  // 验证代币地址是否有效
  const isValidAddToken = !!(addLiquidityForm.token && addLiquidityForm.token.length === 42 && addLiquidityForm.token.startsWith('0x'))
  const isValidRemoveToken = !!(removeLiquidityForm.token && removeLiquidityForm.token.length === 42 && removeLiquidityForm.token.startsWith('0x'))
  const isValidSwapTokenIn = !!(swapForm.tokenIn && swapForm.tokenIn.length === 42 && swapForm.tokenIn.startsWith('0x'))
  const isValidSwapTokenOut = !!(swapForm.tokenOut && swapForm.tokenOut.length === 42 && swapForm.tokenOut.startsWith('0x'))

  // 追踪 isProcessing 变化，用于在交易完成后刷新授权
  const prevIsProcessingRef = useRef(isProcessing)

  // 读取授权额度
  const { data: tokenAllowance, refetch: refetchTokenAllowance } = useReadContract({
    address: isValidAddToken ? (addLiquidityForm.token as `0x${string}`) : undefined,
    abi: USDC_ABI,
    functionName: 'allowance',
    args: address && isValidAddToken ? [address, CONTRACTS.YT_REWARD_ROUTER] : undefined,
    query: { enabled: !!address && isValidAddToken },
  })

  const { data: ytLPAllowance, refetch: refetchYtLPAllowance } = useReadContract({
    address: CONTRACTS.YT_LP_TOKEN,
    abi: USDC_ABI,
    functionName: 'allowance',
    args: address ? [address, CONTRACTS.YT_REWARD_ROUTER] : undefined,
    query: { enabled: !!address },
  })

  const { data: swapAllowance, refetch: refetchSwapAllowance } = useReadContract({
    address: isValidSwapTokenIn ? (swapForm.tokenIn as `0x${string}`) : undefined,
    abi: USDC_ABI,
    functionName: 'allowance',
    args: address && isValidSwapTokenIn ? [address, CONTRACTS.YT_REWARD_ROUTER] : undefined,
    query: { enabled: !!address && isValidSwapTokenIn },
  })

  // 交易完成后刷新授权额度
  useEffect(() => {
    if (prevIsProcessingRef.current && !isProcessing) {
      setTimeout(() => {
        refetchTokenAllowance()
        refetchYtLPAllowance()
        refetchSwapAllowance()
      }, 1000)
    }
    prevIsProcessingRef.current = isProcessing
  }, [isProcessing, refetchTokenAllowance, refetchYtLPAllowance, refetchSwapAllowance])

  // 读取价格
  const { data: addLiquidityTokenPrice } = useReadContract({
    address: CONTRACTS.YT_VAULT,
    abi: YT_VAULT_ABI,
    functionName: 'getMinPrice',
    args: isValidAddToken ? [addLiquidityForm.token as `0x${string}`] : undefined,
    query: { enabled: isValidAddToken },
  })

  const { data: removeLiquidityTokenMaxPrice } = useReadContract({
    address: CONTRACTS.YT_VAULT,
    abi: YT_VAULT_ABI,
    functionName: 'getMaxPrice',
    args: isValidRemoveToken ? [removeLiquidityForm.token as `0x${string}`] : undefined,
    query: { enabled: isValidRemoveToken },
  })

  const { data: swapTokenInMaxPrice } = useReadContract({
    address: CONTRACTS.YT_VAULT,
    abi: YT_VAULT_ABI,
    functionName: 'getMaxPrice',
    args: isValidSwapTokenIn ? [swapForm.tokenIn as `0x${string}`] : undefined,
    query: { enabled: isValidSwapTokenIn },
  })

  const { data: swapTokenOutMinPrice } = useReadContract({
    address: CONTRACTS.YT_VAULT,
    abi: YT_VAULT_ABI,
    functionName: 'getMinPrice',
    args: isValidSwapTokenOut ? [swapForm.tokenOut as `0x${string}`] : undefined,
    query: { enabled: isValidSwapTokenOut },
  })

  const { data: isRewardRouterSwapper } = useReadContract({
    address: CONTRACTS.YT_VAULT,
    abi: YT_VAULT_ABI,
    functionName: 'isSwapper',
    args: [CONTRACTS.YT_REWARD_ROUTER],
  })

  const { data: isRewardRouterHandler } = useReadContract({
    address: CONTRACTS.YT_POOL_MANAGER,
    abi: YT_POOL_MANAGER_ABI,
    functionName: 'isHandler',
    args: [CONTRACTS.YT_REWARD_ROUTER],
  })

  const { data: maxSwapAmountIn } = useReadContract({
    address: CONTRACTS.YT_VAULT,
    abi: YT_VAULT_ABI,
    functionName: 'maxSwapAmounts',
    args: isValidSwapTokenIn ? [swapForm.tokenIn as `0x${string}`] : undefined,
    query: { enabled: isValidSwapTokenIn },
  })

  const { data: isSwapEnabled } = useReadContract({
    address: CONTRACTS.YT_VAULT,
    abi: YT_VAULT_ABI,
    functionName: 'isSwapEnabled',
  })

  const { data: poolAmountOut } = useReadContract({
    address: CONTRACTS.YT_VAULT,
    abi: YT_VAULT_ABI,
    functionName: 'poolAmounts',
    args: isValidSwapTokenOut ? [swapForm.tokenOut as `0x${string}`] : undefined,
    query: { enabled: isValidSwapTokenOut },
  })

  const { data: usdyAmountIn } = useReadContract({
    address: CONTRACTS.YT_VAULT,
    abi: YT_VAULT_ABI,
    functionName: 'usdyAmounts',
    args: isValidSwapTokenIn ? [swapForm.tokenIn as `0x${string}`] : undefined,
    query: { enabled: isValidSwapTokenIn },
  })

  const { data: usdyAmountOut } = useReadContract({
    address: CONTRACTS.YT_VAULT,
    abi: YT_VAULT_ABI,
    functionName: 'usdyAmounts',
    args: isValidSwapTokenOut ? [swapForm.tokenOut as `0x${string}`] : undefined,
    query: { enabled: isValidSwapTokenOut },
  })

  // 计算预估输出
  const addLiquidityPreviewAmount = useMemo(() => {
    if (!addLiquidityForm.amount || !addLiquidityTokenPrice || !ytLPPrice) return null
    if (ytLPPrice === 0n) return null
    try {
      const tokenDecimals = getTokenDecimals(addLiquidityForm.token)
      const amountIn = parseUnits(addLiquidityForm.amount, tokenDecimals)
      const PRECISION_DIFF = 10n ** 12n
      return (amountIn * addLiquidityTokenPrice) / ytLPPrice / PRECISION_DIFF
    } catch {
      return null
    }
  }, [addLiquidityForm.amount, addLiquidityForm.token, addLiquidityTokenPrice, ytLPPrice])

  const removeLiquidityPreviewAmount = useMemo(() => {
    if (!removeLiquidityForm.amount || !ytLPPrice || !removeLiquidityTokenMaxPrice) return null
    if (removeLiquidityTokenMaxPrice === 0n) return null
    try {
      const ytLPAmount = parseUnits(removeLiquidityForm.amount, TOKEN_DECIMALS.YT_LP)
      const PRECISION_DIFF = 10n ** 12n
      return (ytLPAmount * ytLPPrice * PRECISION_DIFF) / removeLiquidityTokenMaxPrice
    } catch {
      return null
    }
  }, [removeLiquidityForm.amount, ytLPPrice, removeLiquidityTokenMaxPrice])

  // 检查是否需要授权
  const needsApproval = () => {
    if (!addLiquidityForm.amount) return false
    try {
      const amount = parseUnits(addLiquidityForm.amount, getTokenDecimals(addLiquidityForm.token))
      if (tokenAllowance === undefined || tokenAllowance === null) return true
      return tokenAllowance < amount
    } catch { return false }
  }

  const needsYtLPApproval = () => {
    if (!removeLiquidityForm.amount) return false
    try {
      const amount = parseUnits(removeLiquidityForm.amount, TOKEN_DECIMALS.YT_LP)
      if (ytLPAllowance === undefined || ytLPAllowance === null) return true
      return ytLPAllowance < amount
    } catch { return false }
  }

  const needsSwapApproval = () => {
    if (!swapForm.amount) return false
    try {
      const amount = parseUnits(swapForm.amount, getTokenDecimals(swapForm.tokenIn))
      if (swapAllowance === undefined || swapAllowance === null) return true
      return swapAllowance < amount
    } catch { return false }
  }

  // 处理函数
  const handleApproveToken = () => {
    if (!address || !addLiquidityForm.amount || !isValidAddToken) return
    const amount = parseUnits(addLiquidityForm.amount, getTokenDecimals(addLiquidityForm.token))
    recordTx('approve', addLiquidityForm.amount, getTokenSymbol(addLiquidityForm.token))
    writeContract({
      address: addLiquidityForm.token as `0x${string}`,
      abi: USDC_ABI,
      functionName: 'approve',
      args: [CONTRACTS.YT_REWARD_ROUTER, amount],
      gas: GAS_CONFIG.SIMPLE,
    })
  }

  const handleApproveYtLP = () => {
    if (!address || !removeLiquidityForm.amount) return
    const amount = parseUnits(removeLiquidityForm.amount, TOKEN_DECIMALS.YT_LP)
    recordTx('approve', removeLiquidityForm.amount, 'ytLP')
    writeContract({
      address: CONTRACTS.YT_LP_TOKEN,
      abi: USDC_ABI,
      functionName: 'approve',
      args: [CONTRACTS.YT_REWARD_ROUTER, amount],
      gas: GAS_CONFIG.SIMPLE,
    })
  }

  const handleApproveSwapToken = () => {
    if (!address || !swapForm.amount || !isValidSwapTokenIn) return
    const amount = parseUnits(swapForm.amount, getTokenDecimals(swapForm.tokenIn))
    recordTx('approve', swapForm.amount, getTokenSymbol(swapForm.tokenIn))
    writeContract({
      address: swapForm.tokenIn as `0x${string}`,
      abi: USDC_ABI,
      functionName: 'approve',
      args: [CONTRACTS.YT_REWARD_ROUTER, amount],
      gas: GAS_CONFIG.SIMPLE,
    })
  }

  const handleAddLiquidity = () => {
    if (!address || !addLiquidityForm.amount || !isValidAddToken) return
    const amount = parseUnits(addLiquidityForm.amount, getTokenDecimals(addLiquidityForm.token))
    const slippageBps = Math.floor(Number(addLiquidityForm.slippage) * 100)
    let minOut = BigInt(0)
    if (addLiquidityPreviewAmount && addLiquidityPreviewAmount > 0n) {
      minOut = (addLiquidityPreviewAmount * BigInt(10000 - slippageBps)) / BigInt(10000)
    }
    recordTx('addLiquidity', addLiquidityForm.amount, getTokenSymbol(addLiquidityForm.token))
    writeContract({
      address: CONTRACTS.YT_REWARD_ROUTER,
      abi: YT_REWARD_ROUTER_ABI,
      functionName: 'addLiquidity',
      args: [addLiquidityForm.token as `0x${string}`, amount, minOut, BigInt(0)],
      gas: GAS_CONFIG.COMPLEX,
    })
  }

  const handleRemoveLiquidity = () => {
    if (!address || !removeLiquidityForm.amount || !isValidRemoveToken) return
    const amount = parseUnits(removeLiquidityForm.amount, TOKEN_DECIMALS.YT_LP)
    const slippageBps = Math.floor(Number(removeLiquidityForm.slippage) * 100)
    let minOut = BigInt(0)
    if (removeLiquidityPreviewAmount && removeLiquidityPreviewAmount > 0n) {
      minOut = (removeLiquidityPreviewAmount * BigInt(10000 - slippageBps)) / BigInt(10000)
    }
    recordTx('removeLiquidity', removeLiquidityForm.amount, 'ytLP')
    writeContract({
      address: CONTRACTS.YT_REWARD_ROUTER,
      abi: YT_REWARD_ROUTER_ABI,
      functionName: 'removeLiquidity',
      args: [removeLiquidityForm.token as `0x${string}`, amount, minOut, address],
      gas: GAS_CONFIG.COMPLEX,
    })
  }

  const handleSwap = () => {
    if (!address || !swapForm.amount || !isValidSwapTokenIn || !isValidSwapTokenOut) return
    const tokenInDecimals = getTokenDecimals(swapForm.tokenIn)
    const tokenOutDecimals = getTokenDecimals(swapForm.tokenOut)
    const amount = parseUnits(swapForm.amount, tokenInDecimals)
    const slippageBps = Math.floor(Number(swapForm.slippage) * 100)
    let minOut = BigInt(0)
    if (swapTokenInMaxPrice && swapTokenOutMinPrice && swapTokenOutMinPrice > 0n) {
      const expectedOut = (amount * swapTokenInMaxPrice) / swapTokenOutMinPrice
      const precisionDiff = tokenInDecimals - tokenOutDecimals
      const adjustedOut = precisionDiff > 0
        ? expectedOut / (10n ** BigInt(precisionDiff))
        : expectedOut * (10n ** BigInt(-precisionDiff))
      minOut = (adjustedOut * BigInt(10000 - slippageBps)) / BigInt(10000)
    }
    recordTx('swap', swapForm.amount, `${getTokenSymbol(swapForm.tokenIn)} → ${getTokenSymbol(swapForm.tokenOut)}`)
    writeContract({
      address: CONTRACTS.YT_REWARD_ROUTER,
      abi: YT_REWARD_ROUTER_ABI,
      functionName: 'swapYT',
      args: [
        swapForm.tokenIn as `0x${string}`,
        swapForm.tokenOut as `0x${string}`,
        amount,
        minOut,
        address,
      ],
      gas: GAS_CONFIG.COMPLEX,
    })
  }

  // Add Liquidity 面板内容
  const addLiquidityContent = (
    <div style={{ marginTop: 8 }}>
      <Text type="secondary" style={{ display: 'block', marginBottom: 8, fontSize: 12 }}>{t('lp.addLiquidityDesc')}</Text>

      <Row gutter={8} style={{ marginBottom: 8 }}>
        <Col span={10}>
          <div style={{ fontSize: 11, color: '#666', marginBottom: 2 }}>{'选择代币'}</div>
          <Select
            value={addLiquidityForm.token || undefined}
            onChange={(v) => setAddLiquidityForm({ ...addLiquidityForm, token: v || '' })}
            style={{ width: '100%' }}
            options={whitelistedTokens.map(token => ({ value: token.address, label: `${token.symbol} - ${token.name}` }))}
          />
        </Col>
        <Col span={10}>
          <div style={{ fontSize: 11, color: '#666', marginBottom: 2 }}>{t('lp.amount')}</div>
          <InputNumber
            style={{ width: '100%' }}
            value={Number(addLiquidityForm.amount) || 0}
            onChange={(v) => setAddLiquidityForm({ ...addLiquidityForm, amount: String(v ?? 0) })}
            placeholder="0.0"
          />
        </Col>
        <Col span={4}>
          <div style={{ fontSize: 11, color: '#666', marginBottom: 2 }}>{t('lp.slippage')} (%)</div>
          <InputNumber
            style={{ width: '100%' }}
            value={Number(addLiquidityForm.slippage) || 0}
            onChange={(v) => setAddLiquidityForm({ ...addLiquidityForm, slippage: String(v ?? 0) })}
            placeholder="0.5"
            step={0.1}
          />
        </Col>
      </Row>

      {addLiquidityForm.amount && addLiquidityPreviewAmount && (
        <Alert
          style={{ marginBottom: 12 }}
          message={<>{t('vault.youWillReceive')}: <Text strong style={{ fontSize: 15 }}>{formatUnits(addLiquidityPreviewAmount, TOKEN_DECIMALS.YT_LP)} ytLP</Text></>}
          type="info"
        />
      )}

      {addLiquidityForm.amount && (
        <Alert
          style={{ marginBottom: 12 }}
          type="success"
          message={
            <div style={{ fontSize: 11, fontFamily: 'monospace' }}>
              <div style={{ marginBottom: 4, color: '#666' }}>
                <strong>代币:</strong>{' '}
                {getTokenSymbol(addLiquidityForm.token)} ({addLiquidityForm.token ? `${addLiquidityForm.token.slice(0, 6)}...${addLiquidityForm.token.slice(-4)}` : '未选择'}) |{' '}
                有效: {isValidAddToken ? <Text style={{ color: '#4caf50' }}>是</Text> : <Text style={{ color: '#f44336' }}>否</Text>}
              </div>
              <div style={{ marginBottom: 4, color: '#666' }}>
                <strong>授权:</strong>{' '}
                额度: {tokenAllowance !== undefined ? formatUnits(tokenAllowance, getTokenDecimals(addLiquidityForm.token)) : '加载中'} {getTokenSymbol(addLiquidityForm.token)} |{' '}
                需要: {addLiquidityForm.amount} |{' '}
                需授权: {needsApproval() ? <Text style={{ color: '#f44336' }}>是</Text> : <Text style={{ color: '#4caf50' }}>否</Text>} |{' '}
                处理中: {isProcessing ? <Text style={{ color: '#f44336' }}>是</Text> : <Text style={{ color: '#4caf50' }}>否</Text>}
              </div>
              <div style={{ marginBottom: 4, color: '#555' }}>
                <strong>价格:</strong>{' '}
                tokenMinPrice: {addLiquidityTokenPrice?.toString() || 'N/A'} ({addLiquidityTokenPrice ? (Number(addLiquidityTokenPrice) / 1e30).toFixed(8) : 'N/A'})
              </div>
              <div style={{ color: '#555' }}>
                ytLPPrice: {ytLPPrice?.toString() || 'N/A'} ({ytLPPrice ? (Number(ytLPPrice) / 1e30).toFixed(8) : 'N/A'})
              </div>
              {addLiquidityPreviewAmount && (
                <div style={{ color: '#555' }}>
                  <strong>计算:</strong>{' '}
                  预估: {formatUnits(addLiquidityPreviewAmount, TOKEN_DECIMALS.YT_LP)} ytLP |{' '}
                  minOut: {formatUnits((addLiquidityPreviewAmount * BigInt(10000 - Math.floor(Number(addLiquidityForm.slippage) * 100))) / BigInt(10000), TOKEN_DECIMALS.YT_LP)} ytLP
                </div>
              )}
            </div>
          }
        />
      )}

      <Space style={{ marginBottom: 12 }}>
        {needsApproval() ? (
          <Button size="small" onClick={handleApproveToken} disabled={isProcessing}>
            {isProcessing ? '...' : t('lp.approveToken')}
          </Button>
        ) : (
          <Button type="primary" size="small" onClick={handleAddLiquidity} disabled={isProcessing || !addLiquidityForm.amount}>
            {isProcessing ? '...' : t('lp.addLiquidity')}
          </Button>
        )}
      </Space>
    </div>
  )

  // Remove Liquidity 面板内容
  const removeLiquidityContent = (
    <div style={{ marginTop: 8 }}>
      <Text type="secondary" style={{ display: 'block', marginBottom: 8, fontSize: 12 }}>{t('lp.removeLiquidityDesc')}</Text>

      <Row gutter={8} style={{ marginBottom: 8 }}>
        <Col span={10}>
          <div style={{ fontSize: 11, color: '#666', marginBottom: 2 }}>{t('lp.outputToken')}</div>
          <Select
            value={removeLiquidityForm.token || undefined}
            onChange={(v) => setRemoveLiquidityForm({ ...removeLiquidityForm, token: v || '' })}
            style={{ width: '100%' }}
            options={whitelistedTokens.map(token => ({ value: token.address, label: `${token.symbol} - ${token.name}` }))}
          />
        </Col>
        <Col span={10}>
          <div style={{ fontSize: 11, color: '#666', marginBottom: 2 }}>{t('lp.ytLPAmount')}</div>
          <div style={{ display: 'flex', gap: 4 }}>
            <InputNumber
              style={{ width: '100%', flex: 1 }}
              value={Number(removeLiquidityForm.amount) || 0}
              onChange={(v) => setRemoveLiquidityForm({ ...removeLiquidityForm, amount: String(v ?? 0) })}
              placeholder="0.0"
            />
            <Button
              type="link"
              size="small"
              onClick={() => setRemoveLiquidityForm({
                ...removeLiquidityForm,
                amount: ytLPBalance ? formatUnits(ytLPBalance, TOKEN_DECIMALS.YT_LP) : '0'
              })}
              style={{ fontSize: 10, padding: '2px 6px' }}
            >
              MAX
            </Button>
          </div>
        </Col>
        <Col span={4}>
          <div style={{ fontSize: 11, color: '#666', marginBottom: 2 }}>{t('lp.slippage')} (%)</div>
          <InputNumber
            style={{ width: '100%' }}
            value={Number(removeLiquidityForm.slippage) || 0}
            onChange={(v) => setRemoveLiquidityForm({ ...removeLiquidityForm, slippage: String(v ?? 0) })}
            placeholder="1"
            step={0.1}
          />
        </Col>
      </Row>

      {removeLiquidityForm.amount && removeLiquidityPreviewAmount && (
        <Alert
          style={{ marginBottom: 12 }}
          message={<>{t('vault.youWillReceive')}: <Text strong style={{ fontSize: 15 }}>{formatUnits(removeLiquidityPreviewAmount, getTokenDecimals(removeLiquidityForm.token))} {getTokenSymbol(removeLiquidityForm.token)}</Text></>}
          type="info"
        />
      )}

      {removeLiquidityForm.amount && (
        <Alert
          style={{ marginBottom: 12 }}
          type="warning"
          message={
            <div style={{ fontSize: 11, fontFamily: 'monospace' }}>
              <div style={{ marginBottom: 4, color: '#666' }}>
                <strong>授权:</strong>{' '}
                ytLP额度: {ytLPAllowance !== undefined ? formatUnits(ytLPAllowance, TOKEN_DECIMALS.YT_LP) : '加载中'} ytLP |{' '}
                需要: {removeLiquidityForm.amount} |{' '}
                需授权: {needsYtLPApproval() ? <Text style={{ color: '#f44336' }}>是</Text> : <Text style={{ color: '#4caf50' }}>否</Text>}
              </div>
              <div style={{ marginBottom: 4, color: '#555' }}>
                <strong>余额:</strong>{' '}
                ytLP余额: {ytLPBalance !== undefined ? formatUnits(ytLPBalance, TOKEN_DECIMALS.YT_LP) : 'N/A'} ytLP
              </div>
              <div style={{ marginBottom: 4, color: '#555' }}>
                <strong>价格:</strong>{' '}
                tokenMaxPrice: {removeLiquidityTokenMaxPrice?.toString() || 'N/A'} ({removeLiquidityTokenMaxPrice ? (Number(removeLiquidityTokenMaxPrice) / 1e30).toFixed(8) : 'N/A'})
              </div>
              <div style={{ color: '#555' }}>
                ytLPPrice: {ytLPPrice?.toString() || 'N/A'} ({ytLPPrice ? (Number(ytLPPrice) / 1e30).toFixed(8) : 'N/A'})
              </div>
              {removeLiquidityPreviewAmount && (
                <div style={{ color: '#555' }}>
                  <strong>计算:</strong>{' '}
                  预估输出原始值: {removeLiquidityPreviewAmount.toString()} | 公式: (ytLPAmount × ytLPPrice × 1e12) / tokenMaxPrice
                </div>
              )}
            </div>
          }
        />
      )}

      <Space style={{ marginBottom: 12 }}>
        {needsYtLPApproval() ? (
          <Button size="small" onClick={handleApproveYtLP} disabled={isProcessing}>
            {isProcessing ? '...' : t('lp.approveYtLP')}
          </Button>
        ) : (
          <Button type="primary" size="small" onClick={handleRemoveLiquidity} disabled={isProcessing || !removeLiquidityForm.amount}>
            {isProcessing ? '...' : t('lp.removeLiquidity')}
          </Button>
        )}
      </Space>
    </div>
  )

  // Swap 面板内容
  const swapContent = (
    <div style={{ marginTop: 8 }}>
      <Text type="secondary" style={{ display: 'block', marginBottom: 8, fontSize: 12 }}>{t('lp.swapDesc')}</Text>

      <Row gutter={8} style={{ marginBottom: 8 }}>
        <Col span={6}>
          <div style={{ fontSize: 11, color: '#666', marginBottom: 2 }}>{t('lp.fromToken')}</div>
          <Select
            value={swapForm.tokenIn || undefined}
            onChange={(v) => setSwapForm({ ...swapForm, tokenIn: v || '' })}
            style={{ width: '100%' }}
            options={whitelistedTokens.map(token => ({ value: token.address, label: token.symbol }))}
          />
        </Col>
        <Col span={6}>
          <div style={{ fontSize: 11, color: '#666', marginBottom: 2 }}>{t('lp.toToken')}</div>
          <Select
            value={swapForm.tokenOut || undefined}
            onChange={(v) => setSwapForm({ ...swapForm, tokenOut: v || '' })}
            style={{ width: '100%' }}
            options={whitelistedTokens.map(token => ({ value: token.address, label: token.symbol }))}
          />
        </Col>
        <Col span={8}>
          <div style={{ fontSize: 11, color: '#666', marginBottom: 2 }}>{t('lp.amount')}</div>
          <InputNumber
            style={{ width: '100%' }}
            value={Number(swapForm.amount) || 0}
            onChange={(v) => setSwapForm({ ...swapForm, amount: String(v ?? 0) })}
            placeholder="0.0"
          />
        </Col>
        <Col span={4}>
          <div style={{ fontSize: 11, color: '#666', marginBottom: 2 }}>{t('lp.slippage')} (%)</div>
          <InputNumber
            style={{ width: '100%' }}
            value={Number(swapForm.slippage) || 0}
            onChange={(v) => setSwapForm({ ...swapForm, slippage: String(v ?? 0) })}
            placeholder="0.5"
            step={0.1}
          />
        </Col>
      </Row>

      {swapForm.tokenIn === swapForm.tokenOut && (
        <Alert
          style={{ marginBottom: 8 }}
          message={t('lp.sameTokenWarning')}
          type="warning"
          showIcon
        />
      )}

      {swapForm.amount && (
        <Alert
          style={{ marginBottom: 12 }}
          type="info"
          message={
            <div style={{ fontSize: 11, fontFamily: 'monospace' }}>
              <div style={{ marginBottom: 4, padding: 4, background: isRewardRouterSwapper && isRewardRouterHandler ? '#e8f5e9' : '#ffebee', borderRadius: 4 }}>
                <strong>⚠️ 权限检查:</strong>{' '}
                RewardRouter是Swapper: {isRewardRouterSwapper === undefined ? '加载中...' : isRewardRouterSwapper ? <Text style={{ color: '#4caf50' }}>✓ 是</Text> : <Text style={{ color: '#f44336' }}>✗ 否 (需管理员配置)</Text>} |{' '}
                RewardRouter是Handler: {isRewardRouterHandler === undefined ? '加载中...' : isRewardRouterHandler ? <Text style={{ color: '#4caf50' }}>✓ 是</Text> : <Text style={{ color: '#f44336' }}>✗ 否 (需管理员配置)</Text>}
              </div>
              {(!isRewardRouterSwapper || !isRewardRouterHandler) && (
                <div style={{ marginBottom: 4, padding: 4, background: '#fff3e0', borderRadius: 4, color: '#e65100' }}>
                  <strong>🔧 解决方案:</strong> 管理员需执行: {!isRewardRouterSwapper && 'setSwapper(RewardRouter, true)'} {!isRewardRouterHandler && 'setHandler(RewardRouter, true)'}
                </div>
              )}
              <div style={{ marginBottom: 4, color: '#666' }}>
                <strong>Swap状态:</strong>{' '}
                isSwapEnabled: {isSwapEnabled === undefined ? '加载中...' : isSwapEnabled ? <Text style={{ color: '#4caf50' }}>✓ 启用</Text> : <Text style={{ color: '#f44336' }}>✗ 禁用</Text>}
              </div>
              <div style={{ marginBottom: 4, color: '#666' }}>
                <strong>池子余额:</strong>{' '}
                {getTokenSymbol(swapForm.tokenOut)}池内: {poolAmountOut !== undefined ? formatUnits(poolAmountOut as bigint, getTokenDecimals(swapForm.tokenOut)) : '加载中'} |{' '}
                {getTokenSymbol(swapForm.tokenIn)} USDY债务: {usdyAmountIn !== undefined ? formatUnits(usdyAmountIn as bigint, TOKEN_DECIMALS_DYNAMIC.USDY) : '加载中'} |{' '}
                {getTokenSymbol(swapForm.tokenOut)} USDY债务: {usdyAmountOut !== undefined ? formatUnits(usdyAmountOut as bigint, TOKEN_DECIMALS_DYNAMIC.USDY) : '加载中'}
              </div>
              <div style={{ marginBottom: 4, color: '#666' }}>
                <strong>授权:</strong>{' '}
                {getTokenSymbol(swapForm.tokenIn)}额度: {swapAllowance !== undefined ? formatUnits(swapAllowance, getTokenDecimals(swapForm.tokenIn)) : '加载中'} |{' '}
                需要: {swapForm.amount} |{' '}
                需授权: {needsSwapApproval() ? <Text style={{ color: '#f44336' }}>是</Text> : <Text style={{ color: '#4caf50' }}>否</Text>}
              </div>
              <div style={{ marginBottom: 4, color: '#666' }}>
                <strong>限额:</strong>{' '}
                maxSwapAmount({getTokenSymbol(swapForm.tokenIn)}): {maxSwapAmountIn !== undefined ? (maxSwapAmountIn === 0n ? '无限制' : formatUnits(maxSwapAmountIn, getTokenDecimals(swapForm.tokenIn))) : '加载中'}
              </div>
              <div style={{ marginBottom: 4, color: '#ff9800' }}>
                <strong>手续费:</strong>{' '}
                swapFee: {swapFee !== undefined ? `${Number(swapFee) / 100}%` : 'N/A'} |{' '}
                taxBps: {taxBasisPoints !== undefined ? `${Number(taxBasisPoints) / 100}%` : 'N/A'} |{' '}
                动态: {dynamicFees ? '是' : '否'} |{' '}
                <Text style={{ color: '#f44336' }}>建议滑点: ≥{swapFee && taxBasisPoints ? `${(Number(swapFee) + Number(taxBasisPoints)) / 100 + 0.5}%` : '2%'}</Text>
              </div>
              <div style={{ marginBottom: 4, color: '#555' }}>
                <strong>TokenIn价格 ({getTokenSymbol(swapForm.tokenIn)}):</strong>{' '}
                maxPrice: {swapTokenInMaxPrice?.toString() || 'N/A'} ({swapTokenInMaxPrice ? (Number(swapTokenInMaxPrice) / 1e30).toFixed(8) : 'N/A'})
              </div>
              <div style={{ marginBottom: 4, color: '#555' }}>
                <strong>TokenOut价格 ({getTokenSymbol(swapForm.tokenOut)}):</strong>{' '}
                minPrice: {swapTokenOutMinPrice?.toString() || 'N/A'} ({swapTokenOutMinPrice ? (Number(swapTokenOutMinPrice) / 1e30).toFixed(8) : 'N/A'})
              </div>
              {swapTokenInMaxPrice && swapTokenOutMinPrice && swapTokenOutMinPrice > 0n && (() => {
                try {
                  const tokenInDecimals = getTokenDecimals(swapForm.tokenIn)
                  const tokenOutDecimals = getTokenDecimals(swapForm.tokenOut)
                  const amount = parseUnits(swapForm.amount, tokenInDecimals)
                  const expectedOut = (amount * swapTokenInMaxPrice) / swapTokenOutMinPrice
                  const precisionDiff = tokenInDecimals - tokenOutDecimals
                  const adjustedOut = precisionDiff > 0
                    ? expectedOut / (10n ** BigInt(precisionDiff))
                    : expectedOut * (10n ** BigInt(-precisionDiff))
                  const slippageBps = Math.floor(Number(swapForm.slippage) * 100)
                  const minOut = (adjustedOut * BigInt(10000 - slippageBps)) / BigInt(10000)
                  return (
                    <div style={{ color: '#555' }}>
                      <strong>计算:</strong>{' '}
                      预期输出: {formatUnits(adjustedOut, tokenOutDecimals)} {getTokenSymbol(swapForm.tokenOut)} |{' '}
                      minOut: {formatUnits(minOut, tokenOutDecimals)} {getTokenSymbol(swapForm.tokenOut)}
                    </div>
                  )
                } catch { return null }
              })()}
              {(!swapTokenInMaxPrice || !swapTokenOutMinPrice) && (
                <div style={{ color: '#f44336' }}>
                  <strong>警告:</strong> 代币价格未加载，minOut将为0！请确保代币价格已在合约中设置。
                </div>
              )}
            </div>
          }
        />
      )}

      <Space style={{ marginBottom: 12 }}>
        {needsSwapApproval() ? (
          <Button size="small" onClick={handleApproveSwapToken} disabled={isProcessing}>
            {isProcessing ? '...' : t('lp.approveToken')}
          </Button>
        ) : (
          <Button
            type="primary"
            size="small"
            onClick={handleSwap}
            disabled={isProcessing || !swapForm.amount || swapForm.tokenIn === swapForm.tokenOut}
          >
            {isProcessing ? '...' : t('lp.swap')}
          </Button>
        )}
      </Space>
    </div>
  )

  return (
    <Tabs
      activeKey={activeTab}
      onChange={(key) => setActiveTab(key as 'add' | 'remove' | 'swap')}
      items={[
        { key: 'add', label: t('lp.addLiquidity'), children: addLiquidityContent },
        { key: 'remove', label: t('lp.removeLiquidity'), children: removeLiquidityContent },
        { key: 'swap', label: t('lp.swapTokens'), children: swapContent },
      ]}
    />
  )
}
