/**
 * LP 代币余额表格组件
 * 显示池子中所有代币的余额、权重、比例等信息
 */

import { useMemo } from 'react'
import { formatUnits } from 'viem'
import { useIntl } from '@umijs/max'
import { ProTable } from '@ant-design/pro-components'
import type { ProColumns } from '@ant-design/pro-components'
import { Table, Tag, Tooltip, Typography } from 'antd'
import { getDecimals, getTokenDecimals } from '@/config/contracts'
import { useChainId } from 'wagmi'
import type { ExtendedPoolToken, AvailableToken } from './useLPPoolData'

const { Text } = Typography

interface TokenWithStats extends ExtendedPoolToken {
  targetRatio: number
  currentRatio: number
  deviation: number
  inPool: boolean
}

interface PoolStats {
  tokens: TokenWithStats[]
  totalUsdy: bigint
  totalWeight: bigint
}

interface LPTokenBalancesProps {
  poolTokens: ExtendedPoolToken[]
  allAvailableTokens?: AvailableToken[]
  totalTokenWeights?: bigint
}

export function LPTokenBalances({ poolTokens, allAvailableTokens, totalTokenWeights }: LPTokenBalancesProps) {
  const { formatMessage } = useIntl()
  const t = (id: string) => formatMessage({ id })
  const chainId = useChainId()
  const TOKEN_DECIMALS = getDecimals(chainId)

  // 计算池子统计数据，合并显示所有代币（池子代币 + Factory代币）
  const poolStats = useMemo((): PoolStats | null => {
    if (!poolTokens || poolTokens.length === 0) {
      // 如果池子没有代币，但有 Factory 代币，也显示
      if (allAvailableTokens && allAvailableTokens.length > 0) {
        const factoryOnlyTokens: TokenWithStats[] = allAvailableTokens
          .filter(t => t.source === 'factory')
          .map(t => ({
            address: t.address as `0x${string}`,
            symbol: t.symbol,
            name: t.name,
            decimals: 18,
            balance: 0n,
            isWhitelisted: t.isWhitelisted,
            usdyAmount: 0n,
            isStable: t.isStable,
            weight: 0n,
            targetRatio: 0,
            currentRatio: 0,
            deviation: 0,
            inPool: false,
          }))
        if (factoryOnlyTokens.length > 0) {
          return { tokens: factoryOnlyTokens, totalUsdy: 0n, totalWeight: 0n }
        }
      }
      return null
    }

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

    // 池子代币
    const poolTokensWithStats: TokenWithStats[] = poolTokens.map(token => {
      const targetRatio = totalWeight > 0n
        ? (Number(token.weight || 0n) / Number(totalWeight)) * 100
        : 0
      const currentRatio = totalUsdy > 0n
        ? (Number(token.usdyAmount || 0n) / Number(totalUsdy)) * 100
        : 0
      const deviation = currentRatio - targetRatio

      return {
        ...token,
        targetRatio,
        currentRatio,
        deviation,
        inPool: true,
      }
    })

    // 添加 Factory 里有但池子里没有的代币
    const poolAddresses = new Set(poolTokens.map(t => t.address.toLowerCase()))
    const factoryOnlyTokens: TokenWithStats[] = (allAvailableTokens || [])
      .filter(t => t.source === 'factory' && !poolAddresses.has(t.address.toLowerCase()))
      .map(t => ({
        address: t.address as `0x${string}`,
        symbol: t.symbol,
        name: t.name,
        decimals: 18,
        balance: 0n,
        isWhitelisted: t.isWhitelisted,
        usdyAmount: 0n,
        isStable: t.isStable,
        weight: 0n,
        targetRatio: 0,
        currentRatio: 0,
        deviation: 0,
        inPool: false,
      }))

    return { tokens: [...poolTokensWithStats, ...factoryOnlyTokens], totalUsdy, totalWeight }
  }, [poolTokens, allAvailableTokens, totalTokenWeights])

  const columns: ProColumns<TokenWithStats>[] = [
    {
      title: <Tooltip title="代币符号 / Token Symbol">{'选择代币'}</Tooltip>,
      dataIndex: 'symbol',
      render: (_, record) => <Text strong style={{ opacity: record.inPool ? 1 : 0.7 }}>{record.symbol}</Text>,
    },
    {
      title: <Tooltip title="是否在白名单中 / Is whitelisted">WL</Tooltip>,
      dataIndex: 'isWhitelisted',
      align: 'center',
      render: (_, record) => record.isWhitelisted
        ? <Tag color="success">✓</Tag>
        : <Tag color="error">✗</Tag>,
    },
    {
      title: <Tooltip title="是否在池子中 / Is in pool">Pool</Tooltip>,
      dataIndex: 'inPool',
      align: 'center',
      render: (_, record) => record.inPool
        ? <Tag color="success">✓</Tag>
        : <Tag color="warning">未添加</Tag>,
    },
    {
      title: <Tooltip title="你的钱包余额 / Your wallet balance">{t('common.balance')}</Tooltip>,
      dataIndex: 'balance',
      align: 'right',
      render: (_, record) => record.balance
        ? Number(formatUnits(record.balance, getTokenDecimals(record.address))).toFixed(2)
        : '0',
    },
    {
      title: <Tooltip title="池中代币价值 / Token value in pool">USDY</Tooltip>,
      dataIndex: 'usdyAmount',
      align: 'right',
      render: (_, record) => record.usdyAmount
        ? Number(formatUnits(record.usdyAmount, TOKEN_DECIMALS.USDY)).toFixed(2)
        : '0',
    },
    {
      title: <Tooltip title="代币权重，用于计算目标比例 / Token weight for target ratio">Weight</Tooltip>,
      dataIndex: 'weight',
      align: 'right',
      render: (_, record) => record.weight ? record.weight.toString() : '0',
    },
    {
      title: <Tooltip title="目标比例 = 权重/总权重 / Target ratio = weight/totalWeights">Target</Tooltip>,
      dataIndex: 'targetRatio',
      align: 'right',
      render: (_, record) => `${record.targetRatio.toFixed(1)}%`,
    },
    {
      title: <Tooltip title="当前比例 = USDY数量/总USDY / Current ratio = usdyAmount/totalUsdy">Current</Tooltip>,
      dataIndex: 'currentRatio',
      align: 'right',
      render: (_, record) => `${record.currentRatio.toFixed(1)}%`,
    },
    {
      title: <Tooltip title="偏差 = 当前 - 目标。正值：代币过多（卖出费率高）。负值：代币不足（买入费率低）">Deviation</Tooltip>,
      dataIndex: 'deviation',
      align: 'right',
      render: (_, record) => {
        const abs = Math.abs(record.deviation)
        const color = abs < 1 ? '#4caf50' : abs < 5 ? '#ff9800' : '#f44336'
        return (
          <Text strong={abs >= 5} style={{ color }}>
            {record.deviation >= 0 ? '+' : ''}{record.deviation.toFixed(1)}%
          </Text>
        )
      },
    },
    {
      title: <Tooltip title="是否稳定币（更低的交换费率 0.04%）">Stable</Tooltip>,
      dataIndex: 'isStable',
      align: 'center',
      render: (_, record) => record.isStable
        ? <Text style={{ color: '#2196f3' }}>Yes</Text>
        : <Text type="secondary">-</Text>,
    },
  ]

  if (!poolStats) {
    return (
      <div style={{ marginTop: 12 }}>
        <Text strong style={{ fontSize: 14, display: 'block', marginBottom: 8 }}>{t('lp.yourTokenBalances')}</Text>
        <Text type="secondary">Loading...</Text>
      </div>
    )
  }

  return (
    <div style={{ marginTop: 12 }}>
      <Text strong style={{ fontSize: 14, display: 'block', marginBottom: 8 }}>{t('lp.yourTokenBalances')}</Text>
      <ProTable<TokenWithStats>
        columns={columns}
        dataSource={poolStats.tokens}
        rowKey="address"
        search={false}
        options={false}
        pagination={false}
        size="small"
        rowClassName={(record) => record.inPool ? '' : 'ant-table-row-dimmed'}
        style={{ opacity: 1 }}
        summary={() => (
          <Table.Summary.Row style={{ background: '#fafafa', fontWeight: 'bold' }}>
            <Table.Summary.Cell index={0}>Total</Table.Summary.Cell>
            <Table.Summary.Cell index={1} align="center">-</Table.Summary.Cell>
            <Table.Summary.Cell index={2} align="center">-</Table.Summary.Cell>
            <Table.Summary.Cell index={3} align="right">-</Table.Summary.Cell>
            <Table.Summary.Cell index={4} align="right">
              {Number(formatUnits(poolStats.totalUsdy, TOKEN_DECIMALS.USDY)).toFixed(2)}
            </Table.Summary.Cell>
            <Table.Summary.Cell index={5} align="right">
              {poolStats.totalWeight.toString()}
            </Table.Summary.Cell>
            <Table.Summary.Cell index={6} align="right">100%</Table.Summary.Cell>
            <Table.Summary.Cell index={7} align="right">100%</Table.Summary.Cell>
            <Table.Summary.Cell index={8} align="right">-</Table.Summary.Cell>
            <Table.Summary.Cell index={9} align="center">-</Table.Summary.Cell>
          </Table.Summary.Row>
        )}
      />
      <Text type="secondary" style={{ fontSize: 12, marginTop: 6, display: 'block' }}>
        Deviation: 偏差值。正值表示该代币过多（卖出费率较高），负值表示不足（买入费率较低）
      </Text>
    </div>
  )
}
