/**
 * LP 管理员操作 Hook
 * 包含 P1-P3 级别的管理功能
 */

import { parseUnits } from 'viem'
import {
  CONTRACTS,
  GAS_CONFIG,
  TOKEN_DECIMALS,
  getTokenDecimals,
  YT_POOL_MANAGER_ABI,
  YT_VAULT_ABI,
  YT_LP_TOKEN_ABI,
  YT_PRICE_FEED_ABI,
  FACTORY_ABI,
  USDY_ABI,
} from '@/config/contracts'
import type {
  CooldownForm,
  SwapFeesForm,
  WithdrawForm,
  AumAdjustForm,
  LimitsForm,
  MaxSwapForm,
  PermissionForm,
  PriceConfigForm,
  VaultConfigForm,
  StableTokenConfig,
} from './types'

interface UseLPAdminActionsProps {
  address: `0x${string}` | undefined
  writeContract: (config: any) => void
  recordTx: (type: string, amount?: string, token?: string) => void
}

export function useLPAdminActions({ address, writeContract, recordTx }: UseLPAdminActionsProps) {

  // ===== P1: 核心配置 =====

  // 设置冷却时间
  const handleSetCooldownDuration = (form: CooldownForm) => {
    if (!address || !form.duration) return
    recordTx('test', form.duration, 'SetCooldownDuration')
    writeContract({
      address: CONTRACTS.YT_POOL_MANAGER,
      abi: YT_POOL_MANAGER_ABI,
      functionName: 'setCooldownDuration',
      args: [BigInt(form.duration)],
      gas: GAS_CONFIG.STANDARD,
      maxFeePerGas: GAS_CONFIG.MAX_FEE_PER_GAS,
      maxPriorityFeePerGas: GAS_CONFIG.MAX_PRIORITY_FEE_PER_GAS,
    })
  }

  // 设置交换手续费
  const handleSetSwapFees = (form: SwapFeesForm) => {
    if (!address) return
    recordTx('test', 'SwapFees', 'SetSwapFees')
    writeContract({
      address: CONTRACTS.YT_VAULT,
      abi: YT_VAULT_ABI,
      functionName: 'setSwapFees',
      args: [
        BigInt(form.swapFee),
        BigInt(form.stableSwapFee),
        BigInt(form.taxBasisPoints),
        BigInt(form.stableTaxBasisPoints)
      ],
      gas: GAS_CONFIG.STANDARD,
      maxFeePerGas: GAS_CONFIG.MAX_FEE_PER_GAS,
      maxPriorityFeePerGas: GAS_CONFIG.MAX_PRIORITY_FEE_PER_GAS,
    })
  }

  // 紧急提取代币
  const handleWithdrawToken = (form: WithdrawForm) => {
    if (!address || !form.token || !form.receiver || !form.amount) return
    recordTx('test', form.amount, 'WithdrawToken')
    writeContract({
      address: CONTRACTS.YT_VAULT,
      abi: YT_VAULT_ABI,
      functionName: 'withdrawToken',
      args: [
        form.token as `0x${string}`,
        form.receiver as `0x${string}`,
        parseUnits(form.amount, getTokenDecimals(form.token))
      ],
      gas: GAS_CONFIG.STANDARD,
      maxFeePerGas: GAS_CONFIG.MAX_FEE_PER_GAS,
      maxPriorityFeePerGas: GAS_CONFIG.MAX_PRIORITY_FEE_PER_GAS,
    })
  }

  // ===== P2: 交易限制 =====

  // 设置动态手续费开关
  const handleSetDynamicFees = (enabled: boolean) => {
    if (!address) return
    recordTx('test', enabled ? 'ON' : 'OFF', 'SetDynamicFees')
    writeContract({
      address: CONTRACTS.YT_VAULT,
      abi: YT_VAULT_ABI,
      functionName: 'setDynamicFees',
      args: [enabled],
      gas: GAS_CONFIG.STANDARD,
      maxFeePerGas: GAS_CONFIG.MAX_FEE_PER_GAS,
      maxPriorityFeePerGas: GAS_CONFIG.MAX_PRIORITY_FEE_PER_GAS,
    })
  }

  // 暂停 LP Pool
  const handlePausePool = () => {
    if (!address) return
    recordTx('test', 'Pause', 'PausePool')
    writeContract({
      address: CONTRACTS.YT_POOL_MANAGER,
      abi: YT_POOL_MANAGER_ABI,
      functionName: 'pause',
      args: [],
      gas: GAS_CONFIG.STANDARD,
      maxFeePerGas: GAS_CONFIG.MAX_FEE_PER_GAS,
      maxPriorityFeePerGas: GAS_CONFIG.MAX_PRIORITY_FEE_PER_GAS,
    })
  }

  // 恢复 LP Pool
  const handleUnpausePool = () => {
    if (!address) return
    recordTx('test', 'Unpause', 'UnpausePool')
    writeContract({
      address: CONTRACTS.YT_POOL_MANAGER,
      abi: YT_POOL_MANAGER_ABI,
      functionName: 'unpause',
      args: [],
      gas: GAS_CONFIG.STANDARD,
      maxFeePerGas: GAS_CONFIG.MAX_FEE_PER_GAS,
      maxPriorityFeePerGas: GAS_CONFIG.MAX_PRIORITY_FEE_PER_GAS,
    })
  }

  // 设置 AUM 调整
  const handleSetAumAdjustment = (form: AumAdjustForm) => {
    if (!address) return
    recordTx('test', `+${form.addition}/-${form.deduction}`, 'SetAumAdjustment')
    writeContract({
      address: CONTRACTS.YT_POOL_MANAGER,
      abi: YT_POOL_MANAGER_ABI,
      functionName: 'setAumAdjustment',
      args: [
        parseUnits(form.addition || '0', TOKEN_DECIMALS.USDY),
        parseUnits(form.deduction || '0', TOKEN_DECIMALS.USDY)
      ],
      gas: GAS_CONFIG.STANDARD,
      maxFeePerGas: GAS_CONFIG.MAX_FEE_PER_GAS,
      maxPriorityFeePerGas: GAS_CONFIG.MAX_PRIORITY_FEE_PER_GAS,
    })
  }

  // 设置最大交换金额
  const handleSetMaxSwapAmount = (form: MaxSwapForm) => {
    if (!address || !form.token || !form.amount) return
    recordTx('test', form.amount, 'SetMaxSwapAmount')
    writeContract({
      address: CONTRACTS.YT_VAULT,
      abi: YT_VAULT_ABI,
      functionName: 'setMaxSwapAmount',
      args: [
        form.token as `0x${string}`,
        parseUnits(form.amount, getTokenDecimals(form.token))
      ],
      gas: GAS_CONFIG.STANDARD,
      maxFeePerGas: GAS_CONFIG.MAX_FEE_PER_GAS,
      maxPriorityFeePerGas: GAS_CONFIG.MAX_PRIORITY_FEE_PER_GAS,
    })
  }

  // 设置最大滑点
  const handleSetMaxSwapSlippageBps = (form: LimitsForm) => {
    if (!address || !form.maxSwapSlippageBps) return
    recordTx('test', form.maxSwapSlippageBps, 'SetMaxSwapSlippageBps')
    writeContract({
      address: CONTRACTS.YT_VAULT,
      abi: YT_VAULT_ABI,
      functionName: 'setMaxSwapSlippageBps',
      args: [BigInt(form.maxSwapSlippageBps)],
      gas: GAS_CONFIG.STANDARD,
      maxFeePerGas: GAS_CONFIG.MAX_FEE_PER_GAS,
      maxPriorityFeePerGas: GAS_CONFIG.MAX_PRIORITY_FEE_PER_GAS,
    })
  }

  // 设置最大价格变化
  const handleSetMaxPriceChangeBps = (form: LimitsForm) => {
    if (!address || !form.maxPriceChangeBps) return
    recordTx('test', form.maxPriceChangeBps, 'SetMaxPriceChangeBps')
    writeContract({
      address: CONTRACTS.YT_VAULT,
      abi: YT_VAULT_ABI,
      functionName: 'setMaxPriceChangeBps',
      args: [BigInt(form.maxPriceChangeBps)],
      gas: GAS_CONFIG.STANDARD,
      maxFeePerGas: GAS_CONFIG.MAX_FEE_PER_GAS,
      maxPriorityFeePerGas: GAS_CONFIG.MAX_PRIORITY_FEE_PER_GAS,
    })
  }

  // ===== P3: 权限管理 =====

  // 设置 PoolManager Gov
  const handleSetPoolManagerGov = (form: PermissionForm) => {
    if (!address || !form.govAddress) return
    recordTx('test', form.govAddress, 'SetPoolManagerGov')
    writeContract({
      address: CONTRACTS.YT_POOL_MANAGER,
      abi: YT_POOL_MANAGER_ABI,
      functionName: 'setGov',
      args: [form.govAddress as `0x${string}`],
      gas: GAS_CONFIG.STANDARD,
      maxFeePerGas: GAS_CONFIG.MAX_FEE_PER_GAS,
      maxPriorityFeePerGas: GAS_CONFIG.MAX_PRIORITY_FEE_PER_GAS,
    })
  }

  // 设置 YTVault Gov
  const handleSetVaultGov = (form: PermissionForm) => {
    if (!address || !form.govAddress) return
    recordTx('test', form.govAddress, 'SetVaultGov')
    writeContract({
      address: CONTRACTS.YT_VAULT,
      abi: YT_VAULT_ABI,
      functionName: 'setGov',
      args: [form.govAddress as `0x${string}`],
      gas: GAS_CONFIG.STANDARD,
      maxFeePerGas: GAS_CONFIG.MAX_FEE_PER_GAS,
      maxPriorityFeePerGas: GAS_CONFIG.MAX_PRIORITY_FEE_PER_GAS,
    })
  }

  // 设置 Handler
  const handleSetHandler = (form: PermissionForm) => {
    if (!address || !form.handlerAddress) return
    recordTx('test', form.handlerAddress, 'SetHandler')
    writeContract({
      address: CONTRACTS.YT_POOL_MANAGER,
      abi: YT_POOL_MANAGER_ABI,
      functionName: 'setHandler',
      args: [form.handlerAddress as `0x${string}`, form.handlerActive],
      gas: GAS_CONFIG.STANDARD,
      maxFeePerGas: GAS_CONFIG.MAX_FEE_PER_GAS,
      maxPriorityFeePerGas: GAS_CONFIG.MAX_PRIORITY_FEE_PER_GAS,
    })
  }

  // 设置 Keeper
  const handleSetKeeper = (form: PermissionForm) => {
    if (!address || !form.keeperAddress) return
    recordTx('test', form.keeperAddress, 'SetKeeper')
    writeContract({
      address: CONTRACTS.YT_VAULT,
      abi: YT_VAULT_ABI,
      functionName: 'setKeeper',
      args: [form.keeperAddress as `0x${string}`, form.keeperActive],
      gas: GAS_CONFIG.STANDARD,
      maxFeePerGas: GAS_CONFIG.MAX_FEE_PER_GAS,
      maxPriorityFeePerGas: GAS_CONFIG.MAX_PRIORITY_FEE_PER_GAS,
    })
  }

  // 设置 Swapper
  const handleSetSwapper = (form: PermissionForm) => {
    if (!address || !form.swapperAddress) return
    recordTx('test', form.swapperAddress, 'SetSwapper')
    writeContract({
      address: CONTRACTS.YT_VAULT,
      abi: YT_VAULT_ABI,
      functionName: 'setSwapper',
      args: [form.swapperAddress as `0x${string}`, form.swapperActive],
      gas: GAS_CONFIG.STANDARD,
      maxFeePerGas: GAS_CONFIG.MAX_FEE_PER_GAS,
      maxPriorityFeePerGas: GAS_CONFIG.MAX_PRIORITY_FEE_PER_GAS,
    })
  }

  // 设置 PoolManager
  const handleSetPoolManager = (form: PermissionForm) => {
    if (!address || !form.poolManagerAddress) return
    recordTx('test', form.poolManagerAddress, 'SetPoolManager')
    writeContract({
      address: CONTRACTS.YT_VAULT,
      abi: YT_VAULT_ABI,
      functionName: 'setPoolManager',
      args: [form.poolManagerAddress as `0x${string}`],
      gas: GAS_CONFIG.STANDARD,
      maxFeePerGas: GAS_CONFIG.MAX_FEE_PER_GAS,
      maxPriorityFeePerGas: GAS_CONFIG.MAX_PRIORITY_FEE_PER_GAS,
    })
  }

  // 设置 ytLP Minter
  const handleSetMinter = (form: PermissionForm) => {
    if (!address || !form.minterAddress) return
    recordTx('test', form.minterAddress, 'SetMinter')
    writeContract({
      address: CONTRACTS.YT_LP_TOKEN,
      abi: YT_LP_TOKEN_ABI,
      functionName: 'setMinter',
      args: [form.minterAddress as `0x${string}`, form.minterActive],
      gas: GAS_CONFIG.STANDARD,
      maxFeePerGas: GAS_CONFIG.MAX_FEE_PER_GAS,
      maxPriorityFeePerGas: GAS_CONFIG.MAX_PRIORITY_FEE_PER_GAS,
    })
  }

  // ===== 价格配置 =====

  // 设置价格
  const handleSetPrice = (form: PriceConfigForm) => {
    if (!address || !form.price) return
    recordTx('test', form.price, 'SetPrice')
    const priceIn30Decimals = parseUnits(form.price, TOKEN_DECIMALS.INTERNAL_PRICE)
    writeContract({
      address: CONTRACTS.YT_PRICE_FEED,
      abi: YT_PRICE_FEED_ABI,
      functionName: 'setPrice',
      args: [form.token as `0x${string}`, priceIn30Decimals],
      gas: GAS_CONFIG.STANDARD,
      maxFeePerGas: GAS_CONFIG.MAX_FEE_PER_GAS,
      maxPriorityFeePerGas: GAS_CONFIG.MAX_PRIORITY_FEE_PER_GAS,
    })
  }

  // 设置价差
  const handleSetSpread = (form: PriceConfigForm) => {
    if (!address || !form.spreadBps) return
    recordTx('test', form.spreadBps, 'SetSpread')
    writeContract({
      address: CONTRACTS.YT_PRICE_FEED,
      abi: YT_PRICE_FEED_ABI,
      functionName: 'setSpreadBasisPoints',
      args: [form.token as `0x${string}`, BigInt(form.spreadBps)],
      gas: GAS_CONFIG.STANDARD,
      maxFeePerGas: GAS_CONFIG.MAX_FEE_PER_GAS,
      maxPriorityFeePerGas: GAS_CONFIG.MAX_PRIORITY_FEE_PER_GAS,
    })
  }

  // 设置白名单代币
  const handleSetWhitelistedToken = (form: VaultConfigForm) => {
    if (!address || !form.token) return
    recordTx('test', form.token, 'SetWhitelistedToken')
    writeContract({
      address: CONTRACTS.YT_VAULT,
      abi: YT_VAULT_ABI,
      functionName: 'setWhitelistedToken',
      args: [
        form.token as `0x${string}`,
        BigInt(form.tokenDecimals),
        BigInt(form.tokenWeight),
        parseUnits(form.maxUsdyAmount, TOKEN_DECIMALS.USDY),
        true
      ],
      gas: GAS_CONFIG.STANDARD,
      maxFeePerGas: GAS_CONFIG.MAX_FEE_PER_GAS,
      maxPriorityFeePerGas: GAS_CONFIG.MAX_PRIORITY_FEE_PER_GAS,
    })
  }

  // 移除白名单代币
  const handleClearWhitelistedToken = (token: string) => {
    if (!address || !token) return
    recordTx('test', token, 'ClearWhitelistedToken')
    writeContract({
      address: CONTRACTS.YT_VAULT,
      abi: YT_VAULT_ABI,
      functionName: 'clearWhitelistedToken',
      args: [token as `0x${string}`],
      gas: GAS_CONFIG.STANDARD,
      maxFeePerGas: GAS_CONFIG.MAX_FEE_PER_GAS,
      maxPriorityFeePerGas: GAS_CONFIG.MAX_PRIORITY_FEE_PER_GAS,
    })
  }

  // 设置 USDC 价格源
  const handleSetUsdcPriceSource = (source: string) => {
    if (!address || !source) return
    recordTx('test', source, 'SetUsdcPriceSource')
    writeContract({
      address: CONTRACTS.YT_PRICE_FEED,
      abi: YT_PRICE_FEED_ABI,
      functionName: 'setUsdcPriceSource',
      args: [source as `0x${string}`],
      gas: GAS_CONFIG.STANDARD,
      maxFeePerGas: GAS_CONFIG.MAX_FEE_PER_GAS,
      maxPriorityFeePerGas: GAS_CONFIG.MAX_PRIORITY_FEE_PER_GAS,
    })
  }

  // 设置稳定币
  const handleSetStableToken = (config: StableTokenConfig) => {
    if (!address) return
    recordTx('test', config.token, 'SetStableToken')
    writeContract({
      address: CONTRACTS.YT_PRICE_FEED,
      abi: YT_PRICE_FEED_ABI,
      functionName: 'setStableTokens',
      args: [config.token as `0x${string}`, config.isStable],
      gas: GAS_CONFIG.STANDARD,
      maxFeePerGas: GAS_CONFIG.MAX_FEE_PER_GAS,
      maxPriorityFeePerGas: GAS_CONFIG.MAX_PRIORITY_FEE_PER_GAS,
    })
  }

  // 设置紧急模式
  const handleSetEmergencyMode = (enabled: boolean) => {
    if (!address) return
    recordTx('test', enabled ? 'ON' : 'OFF', 'SetEmergencyMode')
    writeContract({
      address: CONTRACTS.YT_VAULT,
      abi: YT_VAULT_ABI,
      functionName: 'setEmergencyMode',
      args: [enabled],
      gas: GAS_CONFIG.STANDARD,
      maxFeePerGas: GAS_CONFIG.MAX_FEE_PER_GAS,
      maxPriorityFeePerGas: GAS_CONFIG.MAX_PRIORITY_FEE_PER_GAS,
    })
  }

  // 设置 Swap 开关
  const handleSetSwapEnabled = (enabled: boolean) => {
    if (!address) return
    recordTx('test', enabled ? 'ON' : 'OFF', 'SetSwapEnabled')
    writeContract({
      address: CONTRACTS.YT_VAULT,
      abi: YT_VAULT_ABI,
      functionName: 'setSwapEnabled',
      args: [enabled],
      gas: GAS_CONFIG.STANDARD,
      maxFeePerGas: GAS_CONFIG.MAX_FEE_PER_GAS,
      maxPriorityFeePerGas: GAS_CONFIG.MAX_PRIORITY_FEE_PER_GAS,
    })
  }

  // 更新 ytPrice
  const handleUpdateYtPrice = (token: string, ytPrice: string, usdcPrice: bigint) => {
    if (!address || !ytPrice || !usdcPrice) return
    recordTx('test', ytPrice, 'UpdateYtPrice')
    const ytPriceIn30Decimals = parseUnits(ytPrice, TOKEN_DECIMALS.INTERNAL_PRICE)
    writeContract({
      address: CONTRACTS.FACTORY,
      abi: FACTORY_ABI,
      functionName: 'updateVaultPrices',
      args: [token as `0x${string}`, usdcPrice, ytPriceIn30Decimals],
      gas: GAS_CONFIG.STANDARD,
      maxFeePerGas: GAS_CONFIG.MAX_FEE_PER_GAS,
      maxPriorityFeePerGas: GAS_CONFIG.MAX_PRIORITY_FEE_PER_GAS,
    })
  }

  // USDY 白名单管理
  const handleAddUsdyVault = (vault: string) => {
    if (!address || !vault) return
    recordTx('test', vault, 'AddUsdyVault')
    writeContract({
      address: CONTRACTS.USDY,
      abi: USDY_ABI,
      functionName: 'addVault',
      args: [vault as `0x${string}`],
      gas: GAS_CONFIG.STANDARD,
      maxFeePerGas: GAS_CONFIG.MAX_FEE_PER_GAS,
      maxPriorityFeePerGas: GAS_CONFIG.MAX_PRIORITY_FEE_PER_GAS,
    })
  }

  const handleRemoveUsdyVault = (vault: string) => {
    if (!address || !vault) return
    recordTx('test', vault, 'RemoveUsdyVault')
    writeContract({
      address: CONTRACTS.USDY,
      abi: USDY_ABI,
      functionName: 'removeVault',
      args: [vault as `0x${string}`],
      gas: GAS_CONFIG.STANDARD,
      maxFeePerGas: GAS_CONFIG.MAX_FEE_PER_GAS,
      maxPriorityFeePerGas: GAS_CONFIG.MAX_PRIORITY_FEE_PER_GAS,
    })
  }

  return {
    // P1
    handleSetCooldownDuration,
    handleSetSwapFees,
    handleWithdrawToken,
    // P2
    handleSetDynamicFees,
    handlePausePool,
    handleUnpausePool,
    handleSetAumAdjustment,
    handleSetMaxSwapAmount,
    handleSetMaxSwapSlippageBps,
    handleSetMaxPriceChangeBps,
    // P3
    handleSetPoolManagerGov,
    handleSetVaultGov,
    handleSetHandler,
    handleSetKeeper,
    handleSetSwapper,
    handleSetPoolManager,
    handleSetMinter,
    // 价格配置
    handleSetPrice,
    handleSetSpread,
    handleSetWhitelistedToken,
    handleClearWhitelistedToken,
    handleSetUsdcPriceSource,
    handleSetStableToken,
    handleSetEmergencyMode,
    handleSetSwapEnabled,
    handleUpdateYtPrice,
    // USDY 白名单
    handleAddUsdyVault,
    handleRemoveUsdyVault,
  }
}
