/**
 * LP 流动性池面板 (重构版)
 * 使用拆分的组件和 hooks
 */

import { useState, useCallback, useMemo } from 'react'
import { useTransactions } from '@/context/TransactionContext'
import { TransactionHistory } from '@/components/TransactionHistory'

import { useLPPoolData } from './useLPPoolData'
import { useLPTransactions } from './useLPTransactions'
import { useLPAdminActions } from './useLPAdminActions'
import { LPPoolInfo } from './LPPoolInfo'
import { LPOperations } from './LPOperations'
import { LPTokenBalances } from './LPTokenBalances'
import { LPAdminConfig } from './LPAdminConfig'
import { LPDebugInfo } from './LPDebugInfo'
import { LPUsdyPanel } from './LPUsdyPanel'

export function LPPanelNew() {
  const { transactions, clearHistory } = useTransactions()

  // 使用拆分的 hooks
  const poolData = useLPPoolData()

  // 解构 refetch 函数，这些函数引用是稳定的
  const {
    refetchBalance,
    refetchTokenBalances,
    refetchYtLPTotalSupply,
    refetchYtLPPrice,
    refetchAumInUsdy,
    refetchAccountValue,
    refetchUsdyAmounts,
    refetchTokenWeights,
    refetchEmergencyMode,
    refetchSwapEnabled,
    refetchUsdySupply,
    refetchPoolValue,
    refetchVaultWhitelist,
  } = poolData

  // 使用 useCallback 稳定回调，依赖解构后的稳定函数引用
  const handleSuccess = useCallback(() => {
    // 刷新数据
    refetchBalance()
    refetchTokenBalances()
    refetchYtLPTotalSupply()
    refetchYtLPPrice()
    refetchAumInUsdy()
    refetchAccountValue()
    refetchUsdyAmounts()
    refetchTokenWeights()
    refetchEmergencyMode()
    refetchSwapEnabled()
    refetchUsdySupply()
    refetchPoolValue()
    refetchVaultWhitelist()
  }, [
    refetchBalance, refetchTokenBalances, refetchYtLPTotalSupply, refetchYtLPPrice,
    refetchAumInUsdy, refetchAccountValue, refetchUsdyAmounts, refetchTokenWeights,
    refetchEmergencyMode, refetchSwapEnabled, refetchUsdySupply, refetchPoolValue,
    refetchVaultWhitelist
  ])

  // 使用 useMemo 稳定 callbacks 对象
  const txCallbacks = useMemo(() => ({
    onSuccess: handleSuccess,
  }), [handleSuccess])

  const {
    writeContract,
    recordTx,
    isProcessing,
  } = useLPTransactions(txCallbacks)

  // 管理员操作 - recordTx 需要 cast 为 string 类型
  const adminActions = useLPAdminActions({
    address: poolData.address,
    writeContract,
    recordTx: recordTx as (type: string, amount?: string, token?: string) => void,
  })

  // UI 状态
  const [showAdminConfig, setShowAdminConfig] = useState(false)
  const [showDebugInfo, setShowDebugInfo] = useState(false)
  const [showUsdyPanel, setShowUsdyPanel] = useState(false)

  // 未连接钱包
  if (!poolData.isConnected) {
    return (
      <div className="panel">
        <h2>{t('lp.title')}</h2>
        <p className="text-muted">{t('common.connectFirst')}</p>
      </div>
    )
  }

  return (
    <div className="panel">
      <h2>{t('lp.title')}</h2>

      {/* 池子信息 */}
      <LPPoolInfo
        ytLPName={poolData.ytLPName as string}
        ytLPSymbol={poolData.ytLPSymbol as string}
        ytLPDecimals={poolData.ytLPDecimals as number}
        ytLPBalance={poolData.ytLPBalance as bigint}
        ytLPTotalSupply={poolData.ytLPTotalSupply as bigint}
        ytLPPrice={poolData.ytLPPrice as bigint}
        aumInUsdy={poolData.aumInUsdy as bigint}
        accountValue={poolData.accountValue as bigint}
        cooldownDuration={poolData.cooldownDuration as bigint}
        lastAddedAt={poolData.lastAddedAt as bigint}
        emergencyMode={poolData.emergencyMode as boolean}
        swapEnabled={poolData.swapEnabled as boolean}
        poolValue={poolData.poolValue as bigint}
      />

      {/* 代币余额表格 */}
      <LPTokenBalances
        poolTokens={poolData.poolTokens}
        allAvailableTokens={poolData.allAvailableTokens}
      />

      {/* LP 操作 */}
      <LPOperations
        address={poolData.address}
        poolTokens={poolData.poolTokens}
        ytLPBalance={poolData.ytLPBalance as bigint}
        ytLPPrice={poolData.ytLPPrice as bigint}
        isProcessing={isProcessing}
        writeContract={writeContract}
        recordTx={recordTx}
        getTokenSymbol={poolData.getTokenSymbol}
        swapFee={poolData.swapFee as bigint}
        taxBasisPoints={poolData.taxBasisPoints as bigint}
        dynamicFees={poolData.dynamicFees as boolean}
      />

      {/* 管理员配置 */}
      <LPAdminConfig
        address={poolData.address}
        isProcessing={isProcessing}
        poolPaused={poolData.poolPaused as boolean}
        dynamicFees={poolData.dynamicFees as boolean}
        emergencyMode={poolData.emergencyMode as boolean}
        swapEnabled={poolData.swapEnabled as boolean}
        cooldownDuration={poolData.cooldownDuration as bigint}
        usdcPriceSource={poolData.usdcPriceSource as string}
        availableTokens={poolData.allAvailableTokens}
        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}
        show={showAdminConfig}
        onToggle={() => setShowAdminConfig(!showAdminConfig)}
      />

      {/* USDY 面板 */}
      <LPUsdyPanel
        show={showUsdyPanel}
        onToggle={() => setShowUsdyPanel(!showUsdyPanel)}
      />

      {/* 调试信息 */}
      <LPDebugInfo
        vaultGov={poolData.vaultGov as string}
        poolManagerGov={poolData.poolManagerGov as string}
        show={showDebugInfo}
        onToggle={() => setShowDebugInfo(!showDebugInfo)}
      />

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