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, Select, Row, Col, Alert, message, Tag, Collapse } from 'antd';
import {
  DollarOutlined,
  BankOutlined,
  WalletOutlined,
  WarningOutlined,
  SafetyOutlined,
  ThunderboltOutlined,
  PlusOutlined,
  SettingOutlined,
  PauseCircleOutlined,
  PlayCircleOutlined
} from '@ant-design/icons';
import {
  useAccount,
  usePublicClient,
  useReadContract,
  useReadContracts,
  useWriteContract,
  useWaitForTransactionReceipt,
  useChainId
} from 'wagmi';
import { parseUnits, formatUnits } from 'viem';
import {
  GAS_CONFIG,
  LENDING_ABI,
  USDC_ABI,
  YT_TOKEN_ABI,
  YT_PRICE_FEED_ABI,
  getContracts,
  getDecimals,
  getChainName,
  getBlockExplorer,
} from '@/config/contracts';
import { useTransactions } from '@/context/TransactionContext';
import type { TransactionType } from '@/context/TransactionContext';
import { TransactionHistory } from '@/components/TransactionHistory';

const { Text } = Typography;

// Configurator ABI for reading lending configuration
const CONFIGURATOR_ABI = [
  {
    inputs: [{ internalType: 'address', name: 'lendingProxy', type: 'address' }],
    name: 'getConfiguration',
    outputs: [
      {
        components: [
          { internalType: 'address', name: 'baseToken', type: 'address' },
          { internalType: 'address', name: 'lendingPriceSource', type: 'address' },
          { internalType: 'uint64', name: 'supplyKink', type: 'uint64' },
          { internalType: 'uint64', name: 'supplyPerYearInterestRateSlopeLow', type: 'uint64' },
          { internalType: 'uint64', name: 'supplyPerYearInterestRateSlopeHigh', type: 'uint64' },
          { internalType: 'uint64', name: 'supplyPerYearInterestRateBase', type: 'uint64' },
          { internalType: 'uint64', name: 'borrowKink', type: 'uint64' },
          { internalType: 'uint64', name: 'borrowPerYearInterestRateSlopeLow', type: 'uint64' },
          { internalType: 'uint64', name: 'borrowPerYearInterestRateSlopeHigh', type: 'uint64' },
          { internalType: 'uint64', name: 'borrowPerYearInterestRateBase', type: 'uint64' },
          { internalType: 'uint64', name: 'storeFrontPriceFactor', type: 'uint64' },
          { internalType: 'uint64', name: 'trackingIndexScale', type: 'uint64' },
          { internalType: 'uint104', name: 'baseBorrowMin', type: 'uint104' },
          { internalType: 'uint104', name: 'targetReserves', type: 'uint104' },
          {
            components: [
              { internalType: 'address', name: 'asset', type: 'address' },
              { internalType: 'uint8', name: 'decimals', type: 'uint8' },
              { internalType: 'uint64', name: 'borrowCollateralFactor', type: 'uint64' },
              { internalType: 'uint64', name: 'liquidateCollateralFactor', type: 'uint64' },
              { internalType: 'uint64', name: 'liquidationFactor', type: 'uint64' },
              { internalType: 'uint128', name: 'supplyCap', type: 'uint128' }
            ],
            internalType: 'struct LendingConfiguration.AssetConfig[]',
            name: 'assetConfigs',
            type: 'tuple[]'
          }
        ],
        internalType: 'struct LendingConfiguration.Configuration',
        name: '',
        type: 'tuple'
      }
    ],
    stateMutability: 'view',
    type: 'function'
  },
  {
    inputs: [
      { internalType: 'address', name: 'lendingProxy', type: 'address' },
      {
        components: [
          { internalType: 'address', name: 'asset', type: 'address' },
          { internalType: 'uint8', name: 'decimals', type: 'uint8' },
          { internalType: 'uint64', name: 'borrowCollateralFactor', type: 'uint64' },
          { internalType: 'uint64', name: 'liquidateCollateralFactor', type: 'uint64' },
          { internalType: 'uint64', name: 'liquidationFactor', type: 'uint64' },
          { internalType: 'uint128', name: 'supplyCap', type: 'uint128' }
        ],
        internalType: 'struct LendingConfiguration.AssetConfig',
        name: 'assetConfig',
        type: 'tuple'
      }
    ],
    name: 'addAsset',
    outputs: [],
    stateMutability: 'nonpayable',
    type: 'function'
  },
  {
    inputs: [
      { internalType: 'address', name: 'lendingProxy', type: 'address' },
      {
        components: [
          { internalType: 'address', name: 'asset', type: 'address' },
          { internalType: 'uint8', name: 'decimals', type: 'uint8' },
          { internalType: 'uint64', name: 'borrowCollateralFactor', type: 'uint64' },
          { internalType: 'uint64', name: 'liquidateCollateralFactor', type: 'uint64' },
          { internalType: 'uint64', name: 'liquidationFactor', type: 'uint64' },
          { internalType: 'uint128', name: 'supplyCap', type: 'uint128' }
        ],
        internalType: 'struct LendingConfiguration.AssetConfig',
        name: 'assetConfig',
        type: 'tuple'
      }
    ],
    name: 'updateAsset',
    outputs: [],
    stateMutability: 'nonpayable',
    type: 'function'
  },
  {
    inputs: [
      { internalType: 'address', name: 'lendingProxy', type: 'address' },
      {
        components: [
          { internalType: 'address', name: 'baseToken', type: 'address' },
          { internalType: 'address', name: 'lendingPriceSource', type: 'address' },
          { internalType: 'uint64', name: 'supplyKink', type: 'uint64' },
          { internalType: 'uint64', name: 'supplyPerYearInterestRateSlopeLow', type: 'uint64' },
          { internalType: 'uint64', name: 'supplyPerYearInterestRateSlopeHigh', type: 'uint64' },
          { internalType: 'uint64', name: 'supplyPerYearInterestRateBase', type: 'uint64' },
          { internalType: 'uint64', name: 'borrowKink', type: 'uint64' },
          { internalType: 'uint64', name: 'borrowPerYearInterestRateSlopeLow', type: 'uint64' },
          { internalType: 'uint64', name: 'borrowPerYearInterestRateSlopeHigh', type: 'uint64' },
          { internalType: 'uint64', name: 'borrowPerYearInterestRateBase', type: 'uint64' },
          { internalType: 'uint64', name: 'storeFrontPriceFactor', type: 'uint64' },
          { internalType: 'uint64', name: 'trackingIndexScale', type: 'uint64' },
          { internalType: 'uint104', name: 'baseBorrowMin', type: 'uint104' },
          { internalType: 'uint104', name: 'targetReserves', type: 'uint104' },
          {
            components: [
              { internalType: 'address', name: 'asset', type: 'address' },
              { internalType: 'uint8', name: 'decimals', type: 'uint8' },
              { internalType: 'uint64', name: 'borrowCollateralFactor', type: 'uint64' },
              { internalType: 'uint64', name: 'liquidateCollateralFactor', type: 'uint64' },
              { internalType: 'uint64', name: 'liquidationFactor', type: 'uint64' },
              { internalType: 'uint128', name: 'supplyCap', type: 'uint128' }
            ],
            internalType: 'struct LendingConfiguration.AssetConfig[]',
            name: 'assetConfigs',
            type: 'tuple[]'
          }
        ],
        internalType: 'struct LendingConfiguration.Configuration',
        name: 'configuration',
        type: 'tuple'
      }
    ],
    name: 'setConfiguration',
    outputs: [],
    stateMutability: 'nonpayable',
    type: 'function'
  },
  {
    inputs: [],
    name: 'owner',
    outputs: [{ internalType: 'address', name: '', type: 'address' }],
    stateMutability: 'view',
    type: 'function'
  }
] as const;

// ERC20 Base ABI for reading token symbols
const ERC20_BASE_ABI = [
  {
    inputs: [],
    name: 'symbol',
    outputs: [{ internalType: 'string', name: '', type: 'string' }],
    stateMutability: 'view',
    type: 'function'
  },
  {
    inputs: [],
    name: 'decimals',
    outputs: [{ internalType: 'uint8', name: '', type: 'uint8' }],
    stateMutability: 'view',
    type: 'function'
  }
] as const;

// BigInt 幂运算 helper（避免 ** 被转译成 Math.pow 导致错误）
const bigPow10 = (exp: number | bigint): bigint => {
  const e = typeof exp === 'bigint' ? exp : BigInt(exp);
  let r = 1n;
  for (let i = 0n; i < e; i++) r *= 10n;
  return r;
};

// 清算阈值：$10 (30位精度) = 10 * 10^30
const LIQUIDATION_THRESHOLD = 10n * 1000000000000000000000000000000n;

export default function LendingUserPage() {
  const intl = useIntl();
  const { address, isConnected } = useAccount();
  const chainId = useChainId();
  const CONTRACTS = getContracts(chainId);
  const TOKEN_DECIMALS = getDecimals(chainId);
  const currentChainName = getChainName(chainId);
  const blockExplorer = getBlockExplorer(chainId);
  const publicClient = usePublicClient();

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

  // Tab 状态
  const [activeTab, setActiveTab] = useState('supplyUSDC');

  // 表单状态
  const [supplyUSDCAmount, setSupplyUSDCAmount] = useState('');
  const [withdrawUSDCAmount, setWithdrawUSDCAmount] = useState('');
  const [selectedCollateral, setSelectedCollateral] = useState<string>('');
  const [depositAmount, setDepositAmount] = useState('');
  const [borrowAmount, setBorrowAmount] = useState('');
  const [repayAmount, setRepayAmount] = useState('');
  const [withdrawCollateralAmount, setWithdrawCollateralAmount] = useState('');

  // 清算功能状态
  const [liquidateBorrower, setLiquidateBorrower] = useState('');
  const [batchLiquidateAddresses, setBatchLiquidateAddresses] = useState('');
  const [buyCollateralAsset, setBuyCollateralAsset] = useState('');
  const [buyCollateralBaseAmount, setBuyCollateralBaseAmount] = useState('');
  const [withdrawReservesTo, setWithdrawReservesTo] = useState('');
  const [withdrawReservesAmount, setWithdrawReservesAmount] = useState('');

  // 清算历史监控状态
  const [liquidationHistory, setLiquidationHistory] = useState<any[]>([]);
  const [isLoadingHistory, setIsLoadingHistory] = useState(false);
  const [showLiquidationMonitor, setShowLiquidationMonitor] = useState(false);

  // 管理员配置状态
  const [adminSelectedAsset, setAdminSelectedAsset] = useState<string>('');
  const [adminBorrowCollateralFactor, setAdminBorrowCollateralFactor] = useState('75');
  const [adminLiquidateCollateralFactor, setAdminLiquidateCollateralFactor] = useState('85');
  const [adminLiquidationFactor, setAdminLiquidationFactor] = useState('105');
  const [adminSupplyCap, setAdminSupplyCap] = useState('1000000');
  const [adminNewTargetReserves, setAdminNewTargetReserves] = useState('');
  const [adminNewBaseBorrowMin, setAdminNewBaseBorrowMin] = useState('');

  // ===== 读取 assetList（直接从 lendingProxy 读索引 0/1/2）=====
  const { data: assetListData } = useReadContracts({
    contracts: [0, 1, 2].map(i => ({
      address: CONTRACTS.LENDING_PROXY as `0x${string}`,
      abi: LENDING_ABI,
      functionName: 'assetList' as const,
      args: [BigInt(i)] as const,
    }))
  });

  // 读取 baseToken 和 lendingPriceSource
  const { data: baseToken } = useReadContract({
    address: CONTRACTS.LENDING_PROXY,
    abi: LENDING_ABI,
    functionName: 'baseToken',
  });
  const { data: lendingPriceSource } = useReadContract({
    address: CONTRACTS.LENDING_PROXY,
    abi: LENDING_ABI,
    functionName: 'lendingPriceSource',
  });

  // 构建抵押品地址列表（过滤掉未配置的空地址）
  const assetAddresses = useMemo(() => {
    if (!assetListData) return [];
    return assetListData
      .map(item => item.result as `0x${string}` | undefined)
      .filter((addr): addr is `0x${string}` => !!addr && addr !== '0x0000000000000000000000000000000000000000');
  }, [assetListData]);

  // 动态生成抵押品列表（从 assetConfigs 读取详情）
  const assetConfigContracts = useMemo(() => {
    return assetAddresses.map(addr => ({
      address: CONTRACTS.LENDING_PROXY as `0x${string}`,
      abi: LENDING_ABI,
      functionName: 'assetConfigs' as const,
      args: [addr] as const,
    }));
  }, [assetAddresses]);

  const { data: assetConfigsData } = useReadContracts({ contracts: assetConfigContracts });

  const COLLATERAL_ASSETS = useMemo(() => {
    if (assetAddresses.length === 0 || !assetConfigsData) return [];
    return assetAddresses.map((addr, i) => {
      const cfg = assetConfigsData[i]?.result as any;
      return {
        name: `Asset-${i + 1}`,
        address: addr,
        decimals: cfg ? Number(cfg.decimals ?? cfg[1] ?? 18) : 18,
        borrowCollateralFactor: cfg ? (cfg.borrowCollateralFactor ?? cfg[2] ?? 0n) : 0n,
        liquidateCollateralFactor: cfg ? (cfg.liquidateCollateralFactor ?? cfg[3] ?? 0n) : 0n,
        liquidationFactor: cfg ? (cfg.liquidationFactor ?? cfg[4] ?? 0n) : 0n,
      };
    });
  }, [assetAddresses, assetConfigsData]);

  // 读取抵押品 symbols
  const collateralSymbolContracts = useMemo(() => {
    if (!COLLATERAL_ASSETS || COLLATERAL_ASSETS.length === 0) return [];
    return COLLATERAL_ASSETS.map(asset => ({
      address: asset.address,
      abi: ERC20_BASE_ABI,
      functionName: 'symbol' as const,
    }));
  }, [COLLATERAL_ASSETS]);

  const { data: collateralSymbols } = useReadContracts({
    contracts: collateralSymbolContracts
  });

  // 抵押品列表（带 symbol）
  const collateralOptions = useMemo(() => {
    return COLLATERAL_ASSETS.map((asset, index) => ({
      ...asset,
      symbol: collateralSymbols?.[index]?.result as string || asset.name,
    }));
  }, [COLLATERAL_ASSETS, collateralSymbols]);

  // 设置默认选中的抵押品
  useEffect(() => {
    if (collateralOptions.length > 0 && !selectedCollateral) {
      setSelectedCollateral(collateralOptions[0].address);
    }
    if (collateralOptions.length > 0 && !buyCollateralAsset) {
      setBuyCollateralAsset(collateralOptions[0].address);
    }
  }, [collateralOptions, selectedCollateral, buyCollateralAsset]);

  // ===== 读取系统信息 =====
  const { data: systemInfoData, refetch: refetchSystemInfo } = useReadContracts({
    contracts: [
      { address: CONTRACTS.LENDING_PROXY, abi: LENDING_ABI, functionName: 'getTotalSupply' as const },
      { address: CONTRACTS.LENDING_PROXY, abi: LENDING_ABI, functionName: 'getTotalBorrow' as const },
      { address: CONTRACTS.LENDING_PROXY, abi: LENDING_ABI, functionName: 'getUtilization' as const },
      { address: CONTRACTS.LENDING_PROXY, abi: LENDING_ABI, functionName: 'getBorrowRate' as const },
      { address: CONTRACTS.LENDING_PROXY, abi: LENDING_ABI, functionName: 'getReserves' as const },
    ]
  });

  const systemTotalSupply = systemInfoData?.[0]?.result as bigint | undefined;
  const systemTotalBorrow = systemInfoData?.[1]?.result as bigint | undefined;
  const systemUtilization = systemInfoData?.[2]?.result as bigint | undefined;
  const systemBorrowRate = systemInfoData?.[3]?.result as bigint | undefined;
  const systemReserves = systemInfoData?.[4]?.result as bigint | undefined;

  // 读取系统暂停状态
  const { data: isPaused, refetch: refetchPaused } = useReadContract({
    address: CONTRACTS.LENDING_PROXY,
    abi: LENDING_ABI,
    functionName: 'paused'
  });

  // 读取目标储备金
  const { data: targetReservesData } = useReadContract({
    address: CONTRACTS.LENDING_PROXY,
    abi: LENDING_ABI,
    functionName: 'targetReserves'
  });

  // 读取最小借贷数量
  const { data: baseBorrowMinData } = useReadContract({
    address: CONTRACTS.LENDING_PROXY,
    abi: LENDING_ABI,
    functionName: 'baseBorrowMin'
  });

  // 读取 borrowIndex
  const { data: borrowIndexData } = useReadContract({
    address: CONTRACTS.LENDING_PROXY,
    abi: LENDING_ABI,
    functionName: 'borrowIndex'
  });

  // ===== 管理员配置读取 =====
  const { data: lendingConfig, refetch: refetchLendingConfig } = useReadContract({
    address: CONTRACTS.LENDING_CONFIGURATOR,
    abi: CONFIGURATOR_ABI,
    functionName: 'getConfiguration',
    args: [CONTRACTS.LENDING_PROXY]
  });

  const { data: configuratorOwner } = useReadContract({
    address: CONTRACTS.LENDING_CONFIGURATOR,
    abi: CONFIGURATOR_ABI,
    functionName: 'owner',
  });

  const { data: lendingOwner } = useReadContract({
    address: CONTRACTS.LENDING_PROXY,
    abi: LENDING_ABI,
    functionName: 'owner'
  });

  // 利率参数
  const { data: adminBorrowKink } = useReadContract({ address: CONTRACTS.LENDING_PROXY, abi: LENDING_ABI, functionName: 'borrowKink' });
  const { data: adminSupplyKink } = useReadContract({ address: CONTRACTS.LENDING_PROXY, abi: LENDING_ABI, functionName: 'supplyKink' });
  const { data: adminBorrowRateBase } = useReadContract({ address: CONTRACTS.LENDING_PROXY, abi: LENDING_ABI, functionName: 'borrowPerSecondInterestRateBase' });
  const { data: adminBorrowRateSlopeLow } = useReadContract({ address: CONTRACTS.LENDING_PROXY, abi: LENDING_ABI, functionName: 'borrowPerSecondInterestRateSlopeLow' });
  const { data: adminBorrowRateSlopeHigh } = useReadContract({ address: CONTRACTS.LENDING_PROXY, abi: LENDING_ABI, functionName: 'borrowPerSecondInterestRateSlopeHigh' });
  const { data: adminSupplyRateBase } = useReadContract({ address: CONTRACTS.LENDING_PROXY, abi: LENDING_ABI, functionName: 'supplyPerSecondInterestRateBase' });
  const { data: adminSupplyRateSlopeLow } = useReadContract({ address: CONTRACTS.LENDING_PROXY, abi: LENDING_ABI, functionName: 'supplyPerSecondInterestRateSlopeLow' });
  const { data: adminSupplyRateSlopeHigh } = useReadContract({ address: CONTRACTS.LENDING_PROXY, abi: LENDING_ABI, functionName: 'supplyPerSecondInterestRateSlopeHigh' });

  // 抵押品选项直接复用 lendingProxy.assetList 已读到的 collateralOptions
  useEffect(() => {
    if (collateralOptions.length > 0 && !adminSelectedAsset) {
      setAdminSelectedAsset(collateralOptions[0].address);
    }
  }, [collateralOptions, adminSelectedAsset]);

  // 权限检查
  const isConfiguratorOwner = !!(address && configuratorOwner &&
    address.toLowerCase() === (configuratorOwner as string).toLowerCase());
  const isLendingOwner = !!(address && lendingOwner &&
    address.toLowerCase() === (lendingOwner as string).toLowerCase());

  // 从直接读取的 assetConfigsData 构建 map（assetConfigsData 是数组格式：[addr,decimals,borrowFactor,liquidateFactor,liquidationFactor,supplyCap]）
  const adminAssetConfigsMap = useMemo(() => {
    const map = new Map<string, any>();
    assetAddresses.forEach((addr, i) => {
      const result = assetConfigsData?.[i]?.result as any;
      if (result) {
        map.set(addr.toLowerCase(), {
          asset: addr,
          decimals: Number(result[1] ?? 18),
          borrowCollateralFactor: result[2] ?? 0n,
          liquidateCollateralFactor: result[3] ?? 0n,
          liquidationFactor: result[4] ?? 0n,
          supplyCap: result[5] ?? 0n,
        });
      }
    });
    return map;
  }, [assetAddresses, assetConfigsData]);

  // 当前选中资产的链上配置（从 map 查找）
  const adminSelectedAssetConfig = useMemo(() => {
    if (!adminSelectedAsset) return null;
    return adminAssetConfigsMap.get(adminSelectedAsset.toLowerCase()) || null;
  }, [adminAssetConfigsMap, adminSelectedAsset]);

  interface AdminAssetConfig {
    address: string;
    symbol: string;
    decimals: number;
    borrowCollateralFactor: string;
    liquidateCollateralFactor: string;
    liquidationFactor: string;
    supplyCap: string;
  }

  const adminAssetConfigList: AdminAssetConfig[] = useMemo(() => {
    return Array.from(adminAssetConfigsMap.entries()).map(([addr, cfg]) => {
      const tokenInfo = collateralOptions.find(a => a.address.toLowerCase() === addr);
      const symbol = tokenInfo?.symbol || tokenInfo?.name || `${addr.slice(0, 6)}...${addr.slice(-4)}`;
      const decimals = tokenInfo?.decimals || cfg.decimals || 18;
      return {
        address: cfg.asset,
        symbol,
        decimals,
        borrowCollateralFactor: (Number(cfg.borrowCollateralFactor) / 1e16).toFixed(2),
        liquidateCollateralFactor: (Number(cfg.liquidateCollateralFactor) / 1e16).toFixed(2),
        liquidationFactor: (Number(cfg.liquidationFactor) / 1e16).toFixed(2),
        supplyCap: (Number(cfg.supplyCap) / (10 ** decimals)).toLocaleString(),
      };
    });
  }, [adminAssetConfigsMap, collateralOptions]);

  const adminToPercentage = (value: bigint | undefined) => {
    if (!value) return '0.00';
    return (Number(value) / 1e16).toFixed(2);
  };

  const adminColumns: ProColumns<AdminAssetConfig>[] = [
    { title: '代币', dataIndex: 'symbol', width: 120 },
    {
      title: '地址', dataIndex: 'address', width: 150,
      render: (_, record) => <Text code style={{ fontSize: 14 }}>{`${record.address.slice(0, 6)}...${record.address.slice(-4)}`}</Text>,
    },
    { title: '精度', dataIndex: 'decimals', width: 80 },
    { title: '借贷系数', dataIndex: 'borrowCollateralFactor', width: 100, render: (_, record) => <Tag color="blue">{record.borrowCollateralFactor}%</Tag> },
    { title: '清算系数', dataIndex: 'liquidateCollateralFactor', width: 100, render: (_, record) => <Tag color="orange">{record.liquidateCollateralFactor}%</Tag> },
    { title: '清算奖励', dataIndex: 'liquidationFactor', width: 100, render: (_, record) => <Tag color="red">{record.liquidationFactor}%</Tag> },
    { title: '供应上限', dataIndex: 'supplyCap', width: 150 },
  ];

  // 管理员 write hook
  const { writeContract: writeAdminContract, data: adminHash, isPending: isAdminPending } = useWriteContract();
  const { isLoading: isAdminConfirming, isSuccess: isAdminSuccess } = useWaitForTransactionReceipt({ hash: adminHash });

  useEffect(() => {
    if (isAdminSuccess) {
      message.success('交易确认成功！');
      setTimeout(() => {
        refetchLendingConfig();
        refetchPaused();
        refetchSystemInfo();
      }, 2000);
    }
  }, [isAdminSuccess]);

  const isAdminProcessing = isAdminPending || isAdminConfirming;

  // 管理员操作函数
  const handleTogglePause = (pause: boolean) => {
    if (!isLendingOwner) { message.error('只有 Lending Owner 可以执行此操作'); return; }
    writeAdminContract({ address: CONTRACTS.LENDING_PROXY, abi: LENDING_ABI, functionName: pause ? 'pause' : 'unpause', gas: GAS_CONFIG.SIMPLE });
  };

  const handleInitBaseConfig = () => {
    if (!isConfiguratorOwner) { message.error('只有 Configurator Owner 可以执行此操作'); return; }
    const newConfig = {
      baseToken: CONTRACTS.USDC,
      lendingPriceSource: CONTRACTS.LENDING_PRICE_FEED,
      supplyKink: BigInt(8e17),
      supplyPerYearInterestRateSlopeLow: BigInt(5e16),
      supplyPerYearInterestRateSlopeHigh: BigInt(2e17),
      supplyPerYearInterestRateBase: BigInt(0),
      borrowKink: BigInt(8e17),
      borrowPerYearInterestRateSlopeLow: BigInt(8e16),
      borrowPerYearInterestRateSlopeHigh: BigInt(4e17),
      borrowPerYearInterestRateBase: BigInt(2e16),
      storeFrontPriceFactor: BigInt(1e18),
      trackingIndexScale: BigInt(1e15),
      baseBorrowMin: BigInt(1e6),
      targetReserves: BigInt(1e10),
      assetConfigs: lendingConfig?.assetConfigs || []
    };
    writeAdminContract({ address: CONTRACTS.LENDING_CONFIGURATOR, abi: CONFIGURATOR_ABI, functionName: 'setConfiguration', args: [CONTRACTS.LENDING_PROXY, newConfig as any], gas: GAS_CONFIG.STANDARD });
    message.info('正在初始化基础配置...');
  };

  const handleSetBaseBorrowMin = () => {
    if (!isLendingOwner) { message.error('只有 Lending Owner 可以执行此操作'); return; }
    if (!adminNewBaseBorrowMin) { message.error('请输入最小借贷数量'); return; }
    const rawValue = BigInt(Math.floor(Number(adminNewBaseBorrowMin) * (10 ** TOKEN_DECIMALS.USDC)));
    writeAdminContract({ address: CONTRACTS.LENDING_PROXY, abi: LENDING_ABI, functionName: 'setBaseBorrowMin', args: [rawValue], gas: GAS_CONFIG.SIMPLE });
    message.info(`正在设置最小借贷数量为 ${adminNewBaseBorrowMin} USDC...`);
    setAdminNewBaseBorrowMin('');
  };

  const handleSetTargetReserves = () => {
    if (!isLendingOwner) { message.error('只有 Lending Owner 可以执行此操作'); return; }
    if (!adminNewTargetReserves) { message.error('请输入目标储备金数量'); return; }
    const rawValue = BigInt(Math.floor(Number(adminNewTargetReserves) * (10 ** TOKEN_DECIMALS.USDC)));
    writeAdminContract({ address: CONTRACTS.LENDING_PROXY, abi: LENDING_ABI, functionName: 'setTargetReserves', args: [rawValue], gas: GAS_CONFIG.SIMPLE });
    message.info(`正在设置目标储备金为 ${adminNewTargetReserves} USDC...`);
    setAdminNewTargetReserves('');
  };

  const handleAdminSetConfig = () => {
    if (!isConfiguratorOwner) { message.error('只有 Configurator Owner 可以执行此操作'); return; }
    const selectedAssetInfo = collateralOptions.find(a => a.address === adminSelectedAsset);
    if (!selectedAssetInfo) { message.error('请选择资产'); return; }
    const assetConfig = {
      asset: adminSelectedAsset as `0x${string}`,
      decimals: selectedAssetInfo.decimals,
      borrowCollateralFactor: BigInt(Math.floor(parseFloat(adminBorrowCollateralFactor) * 1e16)),
      liquidateCollateralFactor: BigInt(Math.floor(parseFloat(adminLiquidateCollateralFactor) * 1e16)),
      liquidationFactor: BigInt(Math.floor(parseFloat(adminLiquidationFactor) * 1e16)),
      supplyCap: BigInt(Math.floor(parseFloat(adminSupplyCap) * (10 ** selectedAssetInfo.decimals)))
    };
    const functionName = adminSelectedAssetConfig ? 'updateAsset' : 'addAsset';
    writeAdminContract({ address: CONTRACTS.LENDING_CONFIGURATOR, abi: CONFIGURATOR_ABI, functionName, args: [CONTRACTS.LENDING_PROXY, assetConfig], gas: GAS_CONFIG.STANDARD });
    message.info(`${adminSelectedAssetConfig ? '更新' : '添加'}配置交易已发送`);
  };

  const loadAdminConfig = () => {
    if (adminSelectedAssetConfig) {
      setAdminBorrowCollateralFactor((Number(adminSelectedAssetConfig.borrowCollateralFactor) / 1e16).toString());
      setAdminLiquidateCollateralFactor((Number(adminSelectedAssetConfig.liquidateCollateralFactor) / 1e16).toString());
      setAdminLiquidationFactor((Number(adminSelectedAssetConfig.liquidationFactor) / 1e16).toString());
      const tokenInfo = collateralOptions.find(a => a.address.toLowerCase() === adminSelectedAsset.toLowerCase());
      setAdminSupplyCap((Number(adminSelectedAssetConfig.supplyCap) / (10 ** (tokenInfo?.decimals || 18))).toString());
      message.success('已加载链上配置');
    }
  };

  const adminBaseTokenSet = !!(baseToken && baseToken !== '0x0000000000000000000000000000000000000000');

  // ===== 读取用户数据 =====
  const { data: borrowBalance, refetch: refetchBorrowBalance } = useReadContract({
    address: CONTRACTS.LENDING_PROXY,
    abi: LENDING_ABI,
    functionName: 'borrowBalanceOf',
    args: address ? [address] : undefined,
  });

  const { data: userBasic, refetch: refetchUserBasic } = useReadContract({
    address: CONTRACTS.LENDING_PROXY,
    abi: LENDING_ABI,
    functionName: 'userBasic',
    args: address ? [address] : undefined,
  });

  // 直接读取存款余额（与 webapp 一致，使用 supplyBalanceOf）
  const { data: supplyBalance, refetch: refetchSupplyBalance } = useReadContract({
    address: CONTRACTS.LENDING_PROXY,
    abi: LENDING_ABI,
    functionName: 'supplyBalanceOf',
    args: address ? [address] : undefined,
  });
  // 读取 USDC 余额和授权
  const { data: usdcBalance, refetch: refetchUsdcBalance } = useReadContract({
    address: CONTRACTS.USDC,
    abi: USDC_ABI,
    functionName: 'balanceOf',
    args: address ? [address] : undefined,
  });

  const { data: usdcAllowance, refetch: refetchUsdcAllowance } = useReadContract({
    address: CONTRACTS.USDC,
    abi: USDC_ABI,
    functionName: 'allowance',
    args: address ? [address, CONTRACTS.LENDING_PROXY] : undefined,
  });

  // 读取选中抵押品的数据
  const { data: collateralBalance, refetch: refetchCollateralBalance } = useReadContract({
    address: selectedCollateral as `0x${string}`,
    abi: YT_TOKEN_ABI,
    functionName: 'balanceOf',
    args: address && selectedCollateral ? [address] : undefined,
  });

  const { data: collateralAllowance, refetch: refetchCollateralAllowance } = useReadContract({
    address: selectedCollateral as `0x${string}`,
    abi: YT_TOKEN_ABI,
    functionName: 'allowance',
    args: address && selectedCollateral ? [address, CONTRACTS.LENDING_PROXY] : undefined,
  });

  const { data: collateralDeposited, refetch: refetchCollateralDeposited } = useReadContract({
    address: CONTRACTS.LENDING_PROXY,
    abi: LENDING_ABI,
    functionName: 'userCollateral',
    args: address && selectedCollateral ? [address, selectedCollateral as `0x${string}`] : undefined,
  });

  // ===== 批量读取：userCollateral + 价格（健康因子用）=====
  const hfCollateralContracts = useMemo(() => {
    if (!address || assetAddresses.length === 0) return [];
    return assetAddresses.map(addr => ({
      address: CONTRACTS.LENDING_PROXY as `0x${string}`,
      abi: LENDING_ABI,
      functionName: 'userCollateral' as const,
      args: [address, addr] as const,
    }));
  }, [address, assetAddresses]);

  const { data: hfCollateralData, refetch: refetchHfCollateral } = useReadContracts({ contracts: hfCollateralContracts });

  const hfPriceContracts = useMemo(() => {
    if (!lendingPriceSource || assetAddresses.length === 0 || !baseToken) return [];
    return [baseToken as `0x${string}`, ...assetAddresses].map(addr => ({
      address: lendingPriceSource as `0x${string}`,
      abi: YT_PRICE_FEED_ABI,
      functionName: 'getPrice' as const,
      args: [addr] as const,
    }));
  }, [lendingPriceSource, baseToken, assetAddresses]);

  const { data: hfPriceData, refetch: refetchHfPrices } = useReadContracts({ contracts: hfPriceContracts });

  // 健康因子计算（与 webapp useHealthFactor 公式一致）
  const { totalCollateralValueUSD, healthFactor, availableToBorrow } = useMemo(() => {
    const principal = userBasic !== undefined && userBasic !== null ? (userBasic as bigint) : 0n;
    const borrowIdx = borrowIndexData as bigint | undefined;

    // 无债务
    if (principal >= 0n) {
      return { totalCollateralValueUSD: 0n, healthFactor: BigInt('0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff'), availableToBorrow: 0n };
    }
    if (!borrowIdx || !hfPriceData || hfPriceData.length === 0) {
      return { totalCollateralValueUSD: 0n, healthFactor: 0n, availableToBorrow: 0n };
    }

    // debt = -principal * borrowIndex / 1e18
    const debt = -(principal * borrowIdx) / 1000000000000000000n;
    const basePrice = hfPriceData[0]?.result as bigint | undefined;
    if (!basePrice || basePrice === 0n) {
      return { totalCollateralValueUSD: 0n, healthFactor: 0n, availableToBorrow: 0n };
    }

    // debtValue: debt(USDC_dec) * price(30dec) / 10^USDC_dec → 30dec units
    const USDC_DEC = BigInt(TOKEN_DECIMALS.USDC);
    const debtValue = (debt * basePrice) / bigPow10(USDC_DEC);
    if (debtValue === 0n) {
      return { totalCollateralValueUSD: 0n, healthFactor: BigInt('0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff'), availableToBorrow: 0n };
    }

    let totalCollateralValue = 0n;
    let totalWeightedBorrow = 0n;

    COLLATERAL_ASSETS.forEach((asset, i) => {
      const amount = hfCollateralData?.[i]?.result as bigint | undefined ?? 0n;
      const price = hfPriceData[i + 1]?.result as bigint | undefined;
      if (amount > 0n && price && price > 0n) {
        const assetScale = bigPow10(asset.decimals);
        const collateralValue = (amount * price) / assetScale;
        // liquidateCollateralFactor 1e18精度
        const discounted = (collateralValue * BigInt(asset.liquidateCollateralFactor)) / 1000000000000000000n;
        totalCollateralValue += discounted;
        const borrowWeighted = (collateralValue * BigInt(asset.borrowCollateralFactor)) / 1000000000000000000n;
        totalWeightedBorrow += borrowWeighted;
      }
    });

    // healthFactor = totalCollateralValue * 1e18 / debtValue (1e18精度比率)
    const hf = (totalCollateralValue * 1000000000000000000n) / debtValue;

    // 可借额度 = max(borrowWeighted - debtValue, 0)，转回 USDC 单位
    const maxBorrowValue = totalWeightedBorrow;
    const avail = maxBorrowValue > debtValue
      ? ((maxBorrowValue - debtValue) * bigPow10(USDC_DEC)) / basePrice
      : 0n;

    return { totalCollateralValueUSD: totalCollateralValue, healthFactor: hf, availableToBorrow: avail };
  }, [userBasic, borrowIndexData, hfPriceData, hfCollateralData, COLLATERAL_ASSETS, TOKEN_DECIMALS.USDC]);

  // ===== 清算功能读取 =====
  // 查询借款人是否可清算
  const { data: isLiquidatableData } = useReadContract({
    address: CONTRACTS.LENDING_PROXY,
    abi: LENDING_ABI,
    functionName: 'isLiquidatable',
    args: liquidateBorrower ? [liquidateBorrower as `0x${string}`] : undefined,
    query: { enabled: !!liquidateBorrower }
  });

  // 查询借款人债务余额
  const { data: borrowerDebtBalance } = useReadContract({
    address: CONTRACTS.LENDING_PROXY,
    abi: LENDING_ABI,
    functionName: 'borrowBalanceOf',
    args: liquidateBorrower ? [liquidateBorrower as `0x${string}`] : undefined,
    query: { enabled: !!liquidateBorrower }
  });

  // 读取当前储备金
  const { data: currentReserves } = useReadContract({
    address: CONTRACTS.LENDING_PROXY,
    abi: LENDING_ABI,
    functionName: 'getReserves'
  });

  // 读取抵押品储备（购买功能）
  const { data: collateralReserveData } = useReadContract({
    address: CONTRACTS.LENDING_PROXY,
    abi: LENDING_ABI,
    functionName: 'getCollateralReserves',
    args: buyCollateralAsset ? [buyCollateralAsset as `0x${string}`] : undefined,
    query: { enabled: !!buyCollateralAsset }
  });

  // 读取可购买抵押品数量
  const { data: quoteCollateralData } = useReadContract({
    address: CONTRACTS.LENDING_PROXY,
    abi: LENDING_ABI,
    functionName: 'quoteCollateral',
    args: buyCollateralAsset && buyCollateralBaseAmount
      ? [buyCollateralAsset as `0x${string}`, parseUnits(buyCollateralBaseAmount, TOKEN_DECIMALS.USDC)]
      : undefined,
    query: { enabled: !!buyCollateralAsset && !!buyCollateralBaseAmount }
  });

  // ===== 交易处理 =====
  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(intl.formatMessage({ id: 'pages.toast.txSubmitted' }));
    }
  }, [hash]);

  // 交易成功
  useEffect(() => {
    if (isSuccess) {
      if (pendingTxRef.current) {
        updateTransaction(pendingTxRef.current.id, { status: 'success' });
        message.success(intl.formatMessage({ id: 'pages.toast.txSuccess' }));
        pendingTxRef.current = null;
      }
      refetchBorrowBalance();
      refetchSupplyBalance();
      refetchUserBasic();
      refetchUsdcBalance();
      refetchUsdcAllowance();
      refetchCollateralBalance();
      refetchCollateralAllowance();
      refetchCollateralDeposited();
      refetchHfCollateral();
      refetchHfPrices();
      refetchSystemInfo();
      setSupplyUSDCAmount('');
      setWithdrawUSDCAmount('');
      setDepositAmount('');
      setBorrowAmount('');
      setRepayAmount('');
      setWithdrawCollateralAmount('');
    }
  }, [isSuccess]);

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

  useEffect(() => {
    if (writeError) {
      const errorMsg = typeof writeError === 'string' ? writeError : writeError.message || 'Error';
      message.error(errorMsg);
      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 handleApproveUSDC = (amount: string) => {
    if (!amount) return;
    recordTx('approve', amount, 'USDC');
    writeContract({
      address: CONTRACTS.USDC,
      abi: USDC_ABI,
      functionName: 'approve',
      args: [CONTRACTS.LENDING_PROXY, parseUnits(amount, TOKEN_DECIMALS.USDC)],
      gas: GAS_CONFIG.SIMPLE,
    });
  };

  const handleSupplyUSDC = () => {
    if (!supplyUSDCAmount) return;
    recordTx('supply', supplyUSDCAmount, 'USDC');
    writeContract({
      address: CONTRACTS.LENDING_PROXY,
      abi: LENDING_ABI,
      functionName: 'supply',
      args: [parseUnits(supplyUSDCAmount, TOKEN_DECIMALS.USDC)],
      gas: GAS_CONFIG.STANDARD,
    });
  };

  const handleWithdrawUSDC = () => {
    if (!withdrawUSDCAmount) return;
    recordTx('withdraw', withdrawUSDCAmount, 'USDC');
    writeContract({
      address: CONTRACTS.LENDING_PROXY,
      abi: LENDING_ABI,
      functionName: 'withdraw',
      args: [parseUnits(withdrawUSDCAmount, TOKEN_DECIMALS.USDC)],
      gas: GAS_CONFIG.STANDARD,
    });
  };

  const handleApproveCollateral = () => {
    if (!selectedCollateral || !depositAmount) return;
    const selectedAsset = collateralOptions.find(c => c.address === selectedCollateral);
    recordTx('approve', depositAmount, selectedAsset?.symbol || 'Collateral');
    writeContract({
      address: selectedCollateral as `0x${string}`,
      abi: YT_TOKEN_ABI,
      functionName: 'approve',
      args: [CONTRACTS.LENDING_PROXY, parseUnits(depositAmount, selectedAsset?.decimals || 18)],
      gas: GAS_CONFIG.SIMPLE,
    });
  };

  const handleDepositCollateral = () => {
    if (!depositAmount || !selectedCollateral) return;
    const selectedAsset = collateralOptions.find(c => c.address === selectedCollateral);
    recordTx('deposit', depositAmount, selectedAsset?.symbol || 'Collateral');
    writeContract({
      address: CONTRACTS.LENDING_PROXY,
      abi: LENDING_ABI,
      functionName: 'supplyCollateral',
      args: [
        selectedCollateral as `0x${string}`,
        parseUnits(depositAmount, selectedAsset?.decimals || 18)
      ],
      gas: GAS_CONFIG.STANDARD,
    });
  };

  const handleBorrow = () => {
    if (!borrowAmount) return;
    recordTx('borrow', borrowAmount, 'USDC');
    writeContract({
      address: CONTRACTS.LENDING_PROXY,
      abi: LENDING_ABI,
      functionName: 'borrow',
      args: [parseUnits(borrowAmount, TOKEN_DECIMALS.USDC)],
      gas: GAS_CONFIG.STANDARD,
    });
  };

  const handleRepay = () => {
    if (!repayAmount) return;
    recordTx('repay', repayAmount, 'USDC');
    writeContract({
      address: CONTRACTS.LENDING_PROXY,
      abi: LENDING_ABI,
      functionName: 'repay',
      args: [parseUnits(repayAmount, TOKEN_DECIMALS.USDC)],
      gas: GAS_CONFIG.STANDARD,
    });
  };

  const handleWithdrawCollateral = () => {
    if (!withdrawCollateralAmount || !selectedCollateral) return;
    const selectedAsset = collateralOptions.find(c => c.address === selectedCollateral);
    recordTx('withdraw', withdrawCollateralAmount, selectedAsset?.symbol || 'Collateral');
    writeContract({
      address: CONTRACTS.LENDING_PROXY,
      abi: LENDING_ABI,
      functionName: 'withdrawCollateral',
      args: [
        selectedCollateral as `0x${string}`,
        parseUnits(withdrawCollateralAmount, selectedAsset?.decimals || 18)
      ],
      gas: GAS_CONFIG.STANDARD,
    });
  };

  // ===== 清算功能 =====
  const handleAbsorb = () => {
    if (!address || !liquidateBorrower) return;
    if (!isLiquidatableData) {
      message.warning('该地址当前不可清算');
      return;
    }
    recordTx('transfer', liquidateBorrower, 'Absorb');
    writeContract({
      address: CONTRACTS.LENDING_PROXY,
      abi: LENDING_ABI,
      functionName: 'absorb',
      args: [liquidateBorrower as `0x${string}`],
      gas: GAS_CONFIG.COMPLEX,
    });
  };

  const handleAbsorbMultiple = () => {
    if (!address || !batchLiquidateAddresses) return;
    const addresses = batchLiquidateAddresses
      .split(/[,\s]+/)
      .map(addr => addr.trim())
      .filter(addr => /^0x[a-fA-F0-9]{40}$/.test(addr));
    if (addresses.length === 0) {
      message.warning('请输入有效的地址列表');
      return;
    }
    recordTx('transfer', `${addresses.length} 个地址`, 'AbsorbMultiple');
    writeContract({
      address: CONTRACTS.LENDING_PROXY,
      abi: LENDING_ABI,
      functionName: 'absorbMultiple',
      args: [address, addresses as `0x${string}`[]],
      gas: GAS_CONFIG.COMPLEX,
    });
  };

  const handleBuyCollateral = () => {
    if (!address || !buyCollateralAsset || !buyCollateralBaseAmount) return;
    // 检查储备金状态
    if (currentReserves !== undefined && targetReservesData !== undefined) {
      const reserves = currentReserves as bigint;
      const target = targetReservesData as bigint;
      if (reserves >= target) {
        message.warning('储备金充足，当前无法购买抵押品');
        return;
      }
    }
    if (!collateralReserveData || (collateralReserveData as bigint) === 0n) {
      message.warning('该抵押品储备为空，无法购买');
      return;
    }
    const baseAmount = parseUnits(buyCollateralBaseAmount, TOKEN_DECIMALS.USDC);
    const expectedAmount = quoteCollateralData as bigint || 0n;
    const availableReserve = collateralReserveData as bigint;
    const actualAmount = expectedAmount < availableReserve ? expectedAmount : availableReserve;
    const slippageMultiplier = BigInt(Math.floor(0.98 * 1e18));
    const minAmount = (actualAmount * slippageMultiplier) / BigInt(1e18);

    recordTx('transfer', buyCollateralBaseAmount, 'BuyCollateral');
    writeContract({
      address: CONTRACTS.LENDING_PROXY,
      abi: LENDING_ABI,
      functionName: 'buyCollateral',
      args: [buyCollateralAsset as `0x${string}`, minAmount, baseAmount, address],
      gas: GAS_CONFIG.COMPLEX,
    });
  };

  const handleWithdrawReserves = () => {
    if (!address || !withdrawReservesTo || !withdrawReservesAmount) return;
    const amount = parseUnits(withdrawReservesAmount, TOKEN_DECIMALS.USDC);
    recordTx('transfer', withdrawReservesAmount, 'WithdrawReserves');
    writeContract({
      address: CONTRACTS.LENDING_PROXY,
      abi: LENDING_ABI,
      functionName: 'withdrawReserves',
      args: [withdrawReservesTo as `0x${string}`, amount],
      gas: GAS_CONFIG.STANDARD,
    });
  };

  // ===== 清算历史监控 =====
  useEffect(() => {
    if (!publicClient || !showLiquidationMonitor) return;

    const fetchLiquidationHistory = async () => {
      setIsLoadingHistory(true);
      try {
        const currentBlock = await publicClient.getBlockNumber();
        const fromBlock = currentBlock - 50000n;
        const logs = await publicClient.getLogs({
          address: CONTRACTS.LENDING_PROXY as `0x${string}`,
          event: {
            type: 'event',
            name: 'AbsorbDebt',
            inputs: [
              { type: 'address', indexed: true, name: 'absorber' },
              { type: 'address', indexed: true, name: 'borrower' },
              { type: 'uint256', indexed: false, name: 'basePaidOut' },
              { type: 'uint256', indexed: false, name: 'usdValue' }
            ]
          },
          fromBlock,
          toBlock: currentBlock
        });
        setLiquidationHistory(logs.map((log: any) => ({
          absorber: log.args.absorber,
          borrower: log.args.borrower,
          basePaidOut: log.args.basePaidOut,
          usdValue: log.args.usdValue,
          blockNumber: log.blockNumber,
          transactionHash: log.transactionHash,
        })));
      } catch (error) {
        console.error('Failed to fetch liquidation history:', error);
        setLiquidationHistory([]);
      } finally {
        setIsLoadingHistory(false);
      }
    };

    fetchLiquidationHistory();
  }, [publicClient, showLiquidationMonitor, CONTRACTS.LENDING_PROXY]);

  // ===== 格式化函数 =====
  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 formatAPY = (annualApr: bigint | undefined) => {
    if (!annualApr) return '0.00%';
    const apr = Number(annualApr) / 1e18;
    const perSecond = apr / 31536000;
    const apy = (Math.pow(1 + perSecond, 31536000) - 1) * 100;
    return `${apy.toFixed(2)}%`;
  };

  const formatHealthFactor = () => {
    const MAX = BigInt('0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff');
    if (healthFactor >= MAX / 2n) return '∞';
    if (healthFactor === 0n) return 'N/A';
    const hfNum = Number(formatUnits(healthFactor, 18));
    return hfNum >= 10 ? hfNum.toFixed(1) : hfNum >= 1 ? hfNum.toFixed(2) : hfNum.toFixed(3);
  };

  const healthFactorColor = () => {
    const MAX = BigInt('0xffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffffff');
    if (healthFactor >= MAX / 2n) return '#52c41a';
    if (healthFactor === 0n) return '#888';
    const hfNum = Number(formatUnits(healthFactor, 18));
    if (hfNum < 1.0) return '#ff4d4f';
    if (hfNum < 1.2) return '#fa8c16';
    return '#52c41a';
  };

  // ===== 检查授权 =====
  const needsUSDCApproval = !usdcAllowance || usdcAllowance < parseUnits(supplyUSDCAmount || '0', TOKEN_DECIMALS.USDC);
  const selectedAsset = collateralOptions.find(c => c.address === selectedCollateral);
  const needsCollateralApproval = !collateralAllowance ||
    collateralAllowance < parseUnits(depositAmount || '0', selectedAsset?.decimals || 18);

  const needsUSDCApprovalForBuy = !usdcAllowance ||
    (buyCollateralBaseAmount ? usdcAllowance < parseUnits(buyCollateralBaseAmount, TOKEN_DECIMALS.USDC) : false);

  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.lending.title' })} (${currentChainName})`}
    >
      <Space direction="vertical" size="large" style={{ width: '100%' }}>

        {/* 系统状态 */}
        {isPaused && (
          <Alert message="系统已暂停，所有操作不可用" type="error" showIcon />
        )}

        {/* 系统信息 */}
        <Row gutter={[16, 16]}>
          <Col xs={12} sm={8} md={4}>
            <StatisticCard
              statistic={{
                title: '总存款 (USDC)',
                value: formatBalance(systemTotalSupply),
              }}
            />
          </Col>
          <Col xs={12} sm={8} md={4}>
            <StatisticCard
              statistic={{
                title: '总借款 (USDC)',
                value: formatBalance(systemTotalBorrow),
              }}
            />
          </Col>
          <Col xs={12} sm={8} md={4}>
            <StatisticCard
              statistic={{
                title: '资金利用率',
                value: systemUtilization ? `${(Number(systemUtilization) / 1e16).toFixed(2)}%` : '0.00%',
              }}
            />
          </Col>
          <Col xs={12} sm={8} md={4}>
            <StatisticCard
              statistic={{
                title: '借款利率 (APY)',
                value: formatAPY(systemBorrowRate),
              }}
            />
          </Col>
          <Col xs={12} sm={8} md={4}>
            <StatisticCard
              statistic={{
                title: '储备金 (USDC)',
                value: systemReserves ? formatBalance(systemReserves as bigint) : '0.00',
              }}
            />
          </Col>
          <Col xs={12} sm={8} md={4}>
            <StatisticCard
              statistic={{
                title: '系统状态',
                value: isPaused ? '已暂停' : '运行中',
                valueStyle: { color: isPaused ? '#ff4d4f' : '#52c41a' },
              }}
            />
          </Col>
        </Row>

        {/* 账户概览 */}
        <Row gutter={[16, 16]}>
          <Col xs={24} sm={12} md={6}>
            <StatisticCard
              statistic={{
                title: intl.formatMessage({ id: 'pages.lending.yourSupply' }),
                value: formatBalance(supplyBalance),
                suffix: 'USDC',
              }}
            />
          </Col>
          <Col xs={24} sm={12} md={6}>
            <StatisticCard
              style={{ background: borrowBalance && borrowBalance > 0n ? '#fff7e6' : undefined }}
              statistic={{
                title: intl.formatMessage({ id: 'pages.lending.yourBorrow' }),
                value: formatBalance(borrowBalance),
                suffix: 'USDC',
                valueStyle: { color: borrowBalance && borrowBalance > 0n ? '#fa8c16' : undefined },
              }}
            />
          </Col>
          <Col xs={24} sm={12} md={6}>
            <StatisticCard
              statistic={{
                title: '抵押品总价值 (USD)',
                value: formatBalance(totalCollateralValueUSD, 30),
                suffix: 'USD',
              }}
            />
          </Col>
          <Col xs={24} sm={12} md={6}>
            <StatisticCard
              statistic={{
                title: '健康因子',
                value: formatHealthFactor(),
                valueStyle: { color: healthFactorColor() },
              }}
            />
          </Col>
        </Row>

        {/* 操作标签页 */}
        <ProCard>
          <Tabs
            activeKey={activeTab}
            onChange={setActiveTab}
            items={[
              {
                key: 'supplyUSDC',
                label: <span><BankOutlined /> {intl.formatMessage({ id: 'pages.lending.supply' })} USDC</span>,
                children: (
                  <Space direction="vertical" size="middle" style={{ width: '100%' }}>
                    <Alert
                      message={`${intl.formatMessage({ id: 'pages.common.balance' })}: ${formatBalance(usdcBalance)} USDC`}
                      type="info"
                    />
                    <div>
                      <Text strong>金额</Text>
                      <Input
                        size="large"
                        type="number"
                        value={supplyUSDCAmount}
                        onChange={(e) => setSupplyUSDCAmount(e.target.value)}
                        placeholder={intl.formatMessage({ id: 'pages.vault.enterAmount' })}
                        style={{ marginTop: 8 }}
                      />
                    </div>
                    {needsUSDCApproval ? (
                      <Button type="primary" size="large" onClick={() => handleApproveUSDC(supplyUSDCAmount)} loading={isProcessing} block>
                        {intl.formatMessage({ id: 'pages.vault.approve' })} USDC
                      </Button>
                    ) : (
                      <Button
                        type="primary" size="large" icon={<BankOutlined />}
                        onClick={handleSupplyUSDC} loading={isProcessing}
                        disabled={!supplyUSDCAmount || isProcessing} block
                      >
                        {intl.formatMessage({ id: 'pages.lending.supply' })}
                      </Button>
                    )}
                  </Space>
                ),
              },
              {
                key: 'withdrawUSDC',
                label: <span><DollarOutlined /> {intl.formatMessage({ id: 'pages.lending.withdraw' })} USDC</span>,
                children: (
                  <Space direction="vertical" size="middle" style={{ width: '100%' }}>
                    <Alert message={`已存入: ${formatBalance(supplyBalance)} USDC`} type="info" />
                    <div>
                      <Text strong>提取金额</Text>
                      <Input
                        size="large" type="number" value={withdrawUSDCAmount}
                        onChange={(e) => setWithdrawUSDCAmount(e.target.value)}
                        placeholder={intl.formatMessage({ id: 'pages.vault.enterAmount' })}
                        style={{ marginTop: 8 }}
                      />
                    </div>
                    <Button
                      type="primary" size="large" icon={<DollarOutlined />}
                      onClick={handleWithdrawUSDC} loading={isProcessing}
                      disabled={!withdrawUSDCAmount || isProcessing} block
                    >
                      {intl.formatMessage({ id: 'pages.lending.withdraw' })}
                    </Button>
                  </Space>
                ),
              },
              {
                key: 'deposit',
                label: <span><SafetyOutlined /> 存入抵押品</span>,
                children: (
                  <Space direction="vertical" size="middle" style={{ width: '100%' }}>
                    <div>
                      <Text strong>选择抵押品</Text>
                      <Select
                        size="large"
                        style={{ width: '100%', marginTop: 8 }}
                        value={selectedCollateral}
                        onChange={setSelectedCollateral}
                        options={collateralOptions.map(c => ({
                          label: `${c.symbol} (${c.address.slice(0, 6)}...${c.address.slice(-4)})`,
                          value: c.address
                        }))}
                      />
                    </div>
                    <Alert
                      message={`${intl.formatMessage({ id: 'pages.common.balance' })}: ${formatBalance(collateralBalance, selectedAsset?.decimals || 18)} ${selectedAsset?.symbol || ''}`}
                      type="info"
                    />
                    <div>
                      <Text strong>存入数量</Text>
                      <Input
                        size="large" type="number" value={depositAmount}
                        onChange={(e) => setDepositAmount(e.target.value)}
                        placeholder={intl.formatMessage({ id: 'pages.vault.enterAmount' })}
                        style={{ marginTop: 8 }}
                      />
                    </div>
                    {needsCollateralApproval ? (
                      <Button type="primary" size="large" onClick={handleApproveCollateral} loading={isProcessing} block>
                        {intl.formatMessage({ id: 'pages.vault.approve' })} {selectedAsset?.symbol}
                      </Button>
                    ) : (
                      <Button
                        type="primary" size="large" icon={<SafetyOutlined />}
                        onClick={handleDepositCollateral} loading={isProcessing}
                        disabled={!depositAmount || isProcessing} block
                      >
                        存入抵押品
                      </Button>
                    )}
                  </Space>
                ),
              },
              {
                key: 'borrow',
                label: <span><BankOutlined /> {intl.formatMessage({ id: 'pages.lending.borrow' })}</span>,
                children: (
                  <Space direction="vertical" size="middle" style={{ width: '100%' }}>
                    <Alert
                      message={`抵押品: ${formatBalance(collateralDeposited, selectedAsset?.decimals || 18)} ${selectedAsset?.symbol || ''} | 可借: ${formatBalance(availableToBorrow)} USDC`}
                      type="info"
                    />
                    <div>
                      <Text strong>借款金额 (USDC)</Text>
                      <Input
                        size="large" type="number" value={borrowAmount}
                        onChange={(e) => setBorrowAmount(e.target.value)}
                        placeholder={intl.formatMessage({ id: 'pages.vault.enterAmount' })}
                        style={{ marginTop: 8 }}
                      />
                    </div>
                    <Button
                      type="primary" size="large" icon={<BankOutlined />}
                      onClick={handleBorrow} loading={isProcessing}
                      disabled={!borrowAmount || isProcessing} block
                    >
                      {intl.formatMessage({ id: 'pages.lending.borrow' })}
                    </Button>
                  </Space>
                ),
              },
              {
                key: 'repay',
                label: <span><DollarOutlined /> {intl.formatMessage({ id: 'pages.lending.repay' })}</span>,
                children: (
                  <Space direction="vertical" size="middle" style={{ width: '100%' }}>
                    <Alert message={`当前借款: ${formatBalance(borrowBalance)} USDC`} type="warning" />
                    <div>
                      <Text strong>还款金额</Text>
                      <Input
                        size="large" type="number" value={repayAmount}
                        onChange={(e) => setRepayAmount(e.target.value)}
                        placeholder={intl.formatMessage({ id: 'pages.vault.enterAmount' })}
                        style={{ marginTop: 8 }}
                      />
                    </div>
                    <Button
                      type="primary" size="large" icon={<DollarOutlined />}
                      onClick={handleRepay} loading={isProcessing}
                      disabled={!repayAmount || isProcessing} block
                    >
                      {intl.formatMessage({ id: 'pages.lending.repay' })}
                    </Button>
                  </Space>
                ),
              },
              {
                key: 'withdrawCollateral',
                label: <span><WalletOutlined /> 提取抵押品</span>,
                children: (
                  <Space direction="vertical" size="middle" style={{ width: '100%' }}>
                    <Alert
                      message={`已存入: ${formatBalance(collateralDeposited, selectedAsset?.decimals || 18)} ${selectedAsset?.symbol || ''}`}
                      type="info"
                    />
                    <div>
                      <Text strong>提取数量</Text>
                      <Input
                        size="large" type="number" value={withdrawCollateralAmount}
                        onChange={(e) => setWithdrawCollateralAmount(e.target.value)}
                        placeholder={intl.formatMessage({ id: 'pages.vault.enterAmount' })}
                        style={{ marginTop: 8 }}
                      />
                    </div>
                    <Button
                      type="primary" size="large" icon={<WalletOutlined />}
                      onClick={handleWithdrawCollateral} loading={isProcessing}
                      disabled={!withdrawCollateralAmount || isProcessing} block
                    >
                      提取抵押品
                    </Button>
                  </Space>
                ),
              },
              {
                key: 'buyCollateral',
                label: <span><DollarOutlined /> 购买清算抵押品</span>,
                children: (
                  <Space direction="vertical" size="middle" style={{ width: '100%' }}>
                    <Alert
                      message={
                        <span>
                          当储备金 ({systemReserves !== undefined ? formatBalance(systemReserves as bigint) : '...'} USDC) 低于目标值 ({targetReservesData !== undefined ? `${formatBalance(targetReservesData as bigint)} USDC` : '...'}) 时可购买清算抵押品
                        </span>
                      }
                      type="info"
                    />
                    <div>
                      <Text strong>选择抵押品资产</Text>
                      <Select
                        size="large"
                        style={{ width: '100%', marginTop: 8 }}
                        value={buyCollateralAsset}
                        onChange={setBuyCollateralAsset}
                        options={collateralOptions.map(c => ({
                          label: `${c.symbol} (储备: ${collateralReserveData !== undefined && buyCollateralAsset === c.address ? formatBalance(collateralReserveData as bigint, c.decimals) : '0'})`,
                          value: c.address
                        }))}
                      />
                    </div>
                    <div>
                      <Text strong>支付 USDC 金额</Text>
                      <Input
                        size="large" type="number" value={buyCollateralBaseAmount}
                        onChange={(e) => setBuyCollateralBaseAmount(e.target.value)}
                        placeholder="0.00"
                        style={{ marginTop: 8 }}
                      />
                    </div>
                    {quoteCollateralData !== undefined && buyCollateralBaseAmount && (
                      <Alert
                        message={`预计可购买: ${formatBalance(quoteCollateralData as bigint, 18)} 代币`}
                        type="success"
                      />
                    )}
                    {needsUSDCApprovalForBuy ? (
                      <Button type="primary" size="large" onClick={() => handleApproveUSDC(buyCollateralBaseAmount)} loading={isProcessing} block>
                        1. 授权 USDC
                      </Button>
                    ) : (
                      <Button
                        type="primary" size="large"
                        onClick={handleBuyCollateral} loading={isProcessing}
                        disabled={!buyCollateralAsset || !buyCollateralBaseAmount || isProcessing} block
                      >
                        2. 购买抵押品
                      </Button>
                    )}
                  </Space>
                ),
              },
              {
                key: 'withdrawReserves',
                label: <span><WarningOutlined /> 提取储备金 (管理员)</span>,
                children: (
                  <Space direction="vertical" size="middle" style={{ width: '100%' }}>
                    <Alert
                      message={`当前储备金: ${systemReserves !== undefined ? formatBalance(systemReserves as bigint) : '...'} USDC | 目标: ${targetReservesData !== undefined ? `${formatBalance(targetReservesData as bigint)} USDC` : '...'}`}
                      type="warning"
                    />
                    <div>
                      <Text strong>接收地址</Text>
                      <Input
                        size="large" value={withdrawReservesTo}
                        onChange={(e) => setWithdrawReservesTo(e.target.value)}
                        placeholder="0x..."
                        style={{ marginTop: 8 }}
                      />
                    </div>
                    <div>
                      <Text strong>提取金额 (USDC)</Text>
                      <Input
                        size="large" type="number" value={withdrawReservesAmount}
                        onChange={(e) => setWithdrawReservesAmount(e.target.value)}
                        placeholder="0.00"
                        style={{ marginTop: 8 }}
                      />
                    </div>
                    <Button
                      type="primary" danger size="large"
                      onClick={handleWithdrawReserves} loading={isProcessing}
                      disabled={!withdrawReservesTo || !withdrawReservesAmount || isProcessing} block
                    >
                      提取储备金
                    </Button>
                  </Space>
                ),
              },
            ]}
          />
        </ProCard>

        {/* 清算面板 */}
        <Collapse
          style={{ background: '#fff' }}
          items={[{
            key: 'liquidation',
            label: <span style={{ cursor: 'pointer' }}><ThunderboltOutlined /> 清算面板</span>,
            children: (
              <Space direction="vertical" size="middle" style={{ width: '100%' }}>
                {/* 单个清算 */}
                <ProCard title="单个清算 (absorb)" size="small">
                  <Space direction="vertical" style={{ width: '100%' }}>
                    <div>
                      <Text strong>借款人地址</Text>
                      <Input
                        value={liquidateBorrower}
                        onChange={(e) => setLiquidateBorrower(e.target.value)}
                        placeholder="0x..."
                        style={{ marginTop: 8 }}
                      />
                    </div>
                    {liquidateBorrower && (
                      <Space>
                        <Tag color={isLiquidatableData ? 'red' : 'green'}>
                          {isLiquidatableData ? '可清算' : '不可清算'}
                        </Tag>
                        <Text style={{ fontSize: 14 }}>
                          债务余额: {borrowerDebtBalance ? formatBalance(borrowerDebtBalance as bigint) : '0.00'} USDC
                        </Text>
                      </Space>
                    )}
                    <Button
                      type="primary" danger
                      onClick={handleAbsorb} loading={isProcessing}
                      disabled={!liquidateBorrower || !isLiquidatableData || isProcessing}
                    >
                      执行清算
                    </Button>
                  </Space>
                </ProCard>

                {/* 批量清算 */}
                <ProCard title="批量清算 (absorbMultiple)" size="small">
                  <Space direction="vertical" style={{ width: '100%' }}>
                    <div>
                      <Text strong>借款人地址列表（逗号或空格分隔）</Text>
                      <Input.TextArea
                        value={batchLiquidateAddresses}
                        onChange={(e) => setBatchLiquidateAddresses(e.target.value)}
                        placeholder="0x..., 0x..., 0x..."
                        rows={4}
                        style={{ marginTop: 8 }}
                      />
                    </div>
                    <Button
                      type="primary" danger
                      onClick={handleAbsorbMultiple} loading={isProcessing}
                      disabled={!batchLiquidateAddresses || isProcessing}
                    >
                      批量清算
                    </Button>
                  </Space>
                </ProCard>
              </Space>
            )
          }]}
        />

        {/* 清算历史监控 */}
        <Collapse
          style={{ background: '#fff' }}
          onChange={(keys) => setShowLiquidationMonitor(keys.includes('monitor'))}
          items={[{
            key: 'monitor',
            label: <span style={{ cursor: 'pointer' }}>清算历史监控 (最近 50,000 区块)</span>,
            children: (
              <Space direction="vertical" style={{ width: '100%' }}>
                <div style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center' }}>
                  <Tag color={liquidationHistory.length > 0 ? 'green' : 'orange'}>
                    {liquidationHistory.length > 0 ? `🟢 ${liquidationHistory.length} 笔清算记录` : '🟡 无清算活动'}
                  </Tag>
                  <Button
                    size="small"
                    loading={isLoadingHistory}
                    onClick={() => {
                      setShowLiquidationMonitor(false);
                      setTimeout(() => setShowLiquidationMonitor(true), 100);
                    }}
                  >
                    刷新
                  </Button>
                </div>

                {isLoadingHistory ? (
                  <Text type="secondary">加载中...</Text>
                ) : liquidationHistory.length === 0 ? (
                  <Alert message="过去约 14 小时内无清算记录" type="info" />
                ) : (
                  <ProTable
                    columns={[
                      {
                        title: '被清算人',
                        dataIndex: 'borrower',
                        render: (_, record) => (
                          <Typography.Text code style={{ fontSize: 13 }}>
                            {record.borrower?.slice(0, 6)}...{record.borrower?.slice(-4)}
                          </Typography.Text>
                        ),
                      },
                      {
                        title: '债务 (USDC)',
                        dataIndex: 'basePaidOut',
                        align: 'right',
                        render: (_, record) => (
                          <Typography.Text strong>
                            {(Number(record.basePaidOut || 0n) / 1e6).toFixed(2)}
                          </Typography.Text>
                        ),
                      },
                      {
                        title: '区块',
                        dataIndex: 'blockNumber',
                        align: 'right',
                        render: (_, record) => (
                          <Typography.Text type="secondary">{record.blockNumber?.toString()}</Typography.Text>
                        ),
                      },
                      {
                        title: '交易',
                        dataIndex: 'transactionHash',
                        align: 'center',
                        render: (_, record) => (
                          <a
                            href={`${blockExplorer}/tx/${record.transactionHash}`}
                            target="_blank"
                            rel="noopener noreferrer"
                          >
                            查看 ↗
                          </a>
                        ),
                      },
                    ]}
                    dataSource={liquidationHistory}
                    rowKey={(record, index) => `${record.transactionHash}-${index}`}
                    search={false}
                    options={false}
                    pagination={false}
                    size="small"
                  />
                )}
              </Space>
            )
          }]}
        />

        {/* 管理员配置面板 */}
        <Collapse
            style={{ background: '#fff' }}
            items={[{
              key: 'adminConfig',
              label: <span style={{ cursor: 'pointer' }}>借贷管理员配置</span>,
              children: (
                <Space direction="vertical" size="large" style={{ width: '100%' }}>

                  {/* 协议信息与权限 */}
                  <ProCard title="协议信息">
                    <Space direction="vertical" style={{ width: '100%' }}>
                      <Text><strong>Configurator Owner:</strong> <Text code style={{ fontSize: 14 }}>{configuratorOwner as string || 'Loading...'}</Text></Text>
                      <Text><strong>Lending Owner:</strong> <Text code style={{ fontSize: 14 }}>{lendingOwner as string || 'Loading...'}</Text></Text>
                      <Text>
                        <strong>当前身份:</strong>{' '}
                        {isConfiguratorOwner
                          ? <Tag color="green">Configurator Owner</Tag>
                          : <Tag color="blue">Lending Owner</Tag>
                        }
                      </Text>
                      <Text>
                        <strong>系统状态:</strong>{' '}
                        <Tag color={isPaused ? 'red' : 'green'}>{isPaused ? '已暂停' : '运行中'}</Tag>
                        {isLendingOwner && (
                          <Button
                            size="small"
                            style={{ marginLeft: 8 }}
                            icon={isPaused ? <PlayCircleOutlined /> : <PauseCircleOutlined />}
                            loading={isAdminProcessing}
                            onClick={() => handleTogglePause(!isPaused)}
                          >
                            {isPaused ? '恢复系统' : '暂停系统'}
                          </Button>
                        )}
                      </Text>
                      <Text>
                        <strong>Base Token:</strong>{' '}
                        {adminBaseTokenSet
                          ? <Text code style={{ fontSize: 14 }}>{baseToken as string}</Text>
                          : <Tag color="warning">未设置</Tag>
                        }
                      </Text>
                      <Text>
                        <strong>Price Source:</strong>{' '}
                        {lendingPriceSource && lendingPriceSource !== '0x0000000000000000000000000000000000000000'
                          ? <Text code style={{ fontSize: 14 }}>{lendingPriceSource as string}</Text>
                          : <Tag color="warning">未设置</Tag>
                        }
                      </Text>
                      {!adminBaseTokenSet && isConfiguratorOwner && (
                        <Alert
                          message="基础配置未初始化，存入抵押品功能将无法使用"
                          type="warning"
                          showIcon
                          action={
                            <Button size="small" type="primary" loading={isAdminProcessing} onClick={handleInitBaseConfig}>
                              初始化基础配置
                            </Button>
                          }
                        />
                      )}
                    </Space>
                  </ProCard>

                  {/* 实时利率参数 */}
                  <Collapse
                    style={{ background: '#fafafa' }}
                    items={[{
                      key: 'rates',
                      label: <span style={{ cursor: 'pointer' }}>实时利率配置参数</span>,
                      children: (
                        <Space direction="vertical" style={{ width: '100%' }}>
                          <Text strong>拐点 (Kink)</Text>
                          <Space>
                            <Text><strong>供应拐点:</strong> {adminSupplyKink !== undefined ? `${(Number(adminSupplyKink) / 1e18 * 100).toFixed(1)}%` : 'Loading...'}</Text>
                            <Text><strong>借款拐点:</strong> {adminBorrowKink !== undefined ? `${(Number(adminBorrowKink) / 1e18 * 100).toFixed(1)}%` : 'Loading...'}</Text>
                          </Space>
                          <Text strong>供应利率 (APY，按年换算)</Text>
                          <Space>
                            <Text><strong>基础利率:</strong> {adminSupplyRateBase !== undefined ? `${(Number(adminSupplyRateBase) * 31536000 / 1e18 * 100).toFixed(2)}%` : 'Loading...'}</Text>
                            <Text><strong>拐点前斜率:</strong> {adminSupplyRateSlopeLow !== undefined ? `${(Number(adminSupplyRateSlopeLow) * 31536000 / 1e18 * 100).toFixed(2)}%` : 'Loading...'}</Text>
                            <Text><strong>拐点后斜率:</strong> {adminSupplyRateSlopeHigh !== undefined ? `${(Number(adminSupplyRateSlopeHigh) * 31536000 / 1e18 * 100).toFixed(2)}%` : 'Loading...'}</Text>
                          </Space>
                          <Text strong>借款利率 (APY，按年换算)</Text>
                          <Space>
                            <Text><strong>基础利率:</strong> {adminBorrowRateBase !== undefined ? `${(Number(adminBorrowRateBase) * 31536000 / 1e18 * 100).toFixed(2)}%` : 'Loading...'}</Text>
                            <Text><strong>拐点前斜率:</strong> {adminBorrowRateSlopeLow !== undefined ? `${(Number(adminBorrowRateSlopeLow) * 31536000 / 1e18 * 100).toFixed(2)}%` : 'Loading...'}</Text>
                            <Text><strong>拐点后斜率:</strong> {adminBorrowRateSlopeHigh !== undefined ? `${(Number(adminBorrowRateSlopeHigh) * 31536000 / 1e18 * 100).toFixed(2)}%` : 'Loading...'}</Text>
                          </Space>
                        </Space>
                      )
                    }]}
                  />

                  {/* 目标储备金 */}
                  <ProCard title="目标储备金">
                    <Space direction="vertical" style={{ width: '100%' }}>
                      <Text>
                        <strong>当前目标储备金:</strong>{' '}
                        {targetReservesData ? `${(Number(targetReservesData) / (10 ** TOKEN_DECIMALS.USDC)).toLocaleString()} USDC` : 'N/A'}
                      </Text>
                      <Text type="secondary" style={{ fontSize: 14 }}>提示: 当储备金低于目标值时，用户可以购买清算抵押品</Text>
                      <div style={{ display: 'flex', gap: 8 }}>
                        <Input
                          style={{ flex: 1 }}
                          type="number"
                          value={adminNewTargetReserves}
                          onChange={(e) => setAdminNewTargetReserves(e.target.value)}
                          placeholder="例如: 10000"
                          addonBefore="新目标储备金 (USDC)"
                        />
                        <Button type="primary" loading={isAdminProcessing} disabled={!adminNewTargetReserves} onClick={handleSetTargetReserves}>
                          设置
                        </Button>
                      </div>
                    </Space>
                  </ProCard>

                  {/* 最小借贷数量 */}
                  <ProCard title="最小借贷数量">
                    <Space direction="vertical" style={{ width: '100%' }}>
                      <Text>
                        <strong>当前最小借贷数量:</strong>{' '}
                        {baseBorrowMinData != null ? `${(Number(baseBorrowMinData) / (10 ** TOKEN_DECIMALS.USDC)).toLocaleString()} USDC` : 'N/A'}
                      </Text>
                      <Text type="secondary" style={{ fontSize: 14 }}>提示: 用户借款金额必须大于此最小值</Text>
                      <div style={{ display: 'flex', gap: 8 }}>
                        <Input
                          style={{ flex: 1 }}
                          type="number"
                          value={adminNewBaseBorrowMin}
                          onChange={(e) => setAdminNewBaseBorrowMin(e.target.value)}
                          placeholder="例如: 10"
                          addonBefore="新最小借贷量 (USDC)"
                        />
                        <Button type="primary" loading={isAdminProcessing} disabled={!adminNewBaseBorrowMin} onClick={handleSetBaseBorrowMin}>
                          设置
                        </Button>
                      </div>
                    </Space>
                  </ProCard>

                  {/* 抵押品状态概览 */}
                  <ProCard title="抵押品状态概览">
                    <div style={{ display: 'grid', gridTemplateColumns: 'repeat(auto-fill, minmax(200px, 1fr))', gap: 12 }}>
                      {collateralOptions.map((asset) => {
                        const config = adminAssetConfigsMap.get(asset.address.toLowerCase());
                        return (
                          <div key={asset.address} style={{ padding: 12, border: '1px solid #e8e8e8', borderRadius: 6, background: '#fafafa' }}>
                            <div style={{ fontSize: 14, fontWeight: 'bold', marginBottom: 6, color: '#333' }}>
                              {asset.symbol || asset.name}
                              <Tag color={config ? 'green' : 'default'} style={{ marginLeft: 6, fontSize: 12 }}>
                                {config ? '已配置' : '未配置'}
                              </Tag>
                            </div>
                            {config ? (
                              <div style={{ fontSize: 13, color: '#666', lineHeight: 1.8 }}>
                                <div>借款抵押率: <strong>{adminToPercentage(config.borrowCollateralFactor)}%</strong></div>
                                <div>清算抵押率: <strong>{adminToPercentage(config.liquidateCollateralFactor)}%</strong></div>
                                <div>清算奖励: <strong>{adminToPercentage(config.liquidationFactor)}%</strong></div>
                              </div>
                            ) : (
                              <Text type="secondary" style={{ fontSize: 13 }}>未配置</Text>
                            )}
                          </div>
                        );
                      })}
                    </div>
                  </ProCard>

                  {/* 抵押品配置表单 */}
                  {isConfiguratorOwner && (
                    <ProCard
                      title={adminSelectedAssetConfig ? '更新抵押品配置' : '添加抵押品配置'}
                      extra={
                        <Button icon={<PlusOutlined />} onClick={loadAdminConfig} disabled={!adminSelectedAssetConfig}>
                          加载链上配置
                        </Button>
                      }
                    >
                      <Space direction="vertical" size="middle" style={{ width: '100%' }}>
                        <Alert
                          type="info"
                          message={
                            <div style={{ fontSize: 13 }}>
                              <div><strong>借款抵押率</strong>：用户可按抵押品价值的此百分比借款（75 表示 75%）</div>
                              <div><strong>清算抵押率</strong>：低于此比例时可被清算（85 表示 85%）</div>
                              <div><strong>清算奖励</strong>：清算人获得的奖励比例（105 表示 105%）</div>
                              <div><strong>供应上限</strong>：最大可存入代币数量（如 1000000 = 100万代币）</div>
                            </div>
                          }
                        />
                        <div>
                          <Text strong>选择资产</Text>
                          <div style={{ display: 'flex', gap: 8, marginTop: 8 }}>
                            <Select
                              style={{ flex: 1 }}
                              value={adminSelectedAsset}
                              onChange={setAdminSelectedAsset}
                              options={collateralOptions.map(a => ({
                                label: `${a.symbol || a.name} (${a.address.slice(0, 6)}...${a.address.slice(-4)})`,
                                value: a.address
                              }))}
                            />
                            <Button onClick={() => refetchLendingConfig()}>刷新</Button>
                          </div>
                          {adminSelectedAsset && (
                            <div style={{ marginTop: 8 }}>
                              {adminSelectedAssetConfig ? (
                                <Alert
                                  type="info"
                                  message={`当前链上: 借款 ${adminToPercentage(adminSelectedAssetConfig.borrowCollateralFactor)}% / 清算 ${adminToPercentage(adminSelectedAssetConfig.liquidateCollateralFactor)}% / 奖励 ${adminToPercentage(adminSelectedAssetConfig.liquidationFactor)}%`}
                                  style={{ fontSize: 13 }}
                                />
                              ) : (
                                <Alert type="warning" message="该资产尚未配置，将使用 addAsset 添加" style={{ fontSize: 13 }} />
                              )}
                            </div>
                          )}
                        </div>
                        <div style={{ display: 'grid', gridTemplateColumns: '1fr 1fr', gap: 12 }}>
                          <div>
                            <Text strong>借款抵押率 (%)</Text>
                            <Input type="number" step="0.01" value={adminBorrowCollateralFactor} onChange={(e) => setAdminBorrowCollateralFactor(e.target.value)} placeholder="75" style={{ marginTop: 4 }} />
                          </div>
                          <div>
                            <Text strong>清算抵押率 (%)</Text>
                            <Input type="number" step="0.01" value={adminLiquidateCollateralFactor} onChange={(e) => setAdminLiquidateCollateralFactor(e.target.value)} placeholder="85" style={{ marginTop: 4 }} />
                          </div>
                          <div>
                            <Text strong>清算奖励 (%)</Text>
                            <Input type="number" step="0.01" value={adminLiquidationFactor} onChange={(e) => setAdminLiquidationFactor(e.target.value)} placeholder="105" style={{ marginTop: 4 }} />
                          </div>
                          <div>
                            <Text strong>供应上限（代币数量）</Text>
                            <Input type="number" value={adminSupplyCap} onChange={(e) => setAdminSupplyCap(e.target.value)} placeholder="1000000" style={{ marginTop: 4 }} />
                          </div>
                        </div>
                        <Button
                          type="primary" block loading={isAdminProcessing} disabled={!adminSelectedAsset}
                          onClick={handleAdminSetConfig}
                          icon={adminSelectedAssetConfig ? <SettingOutlined /> : <PlusOutlined />}
                        >
                          {adminSelectedAssetConfig ? '更新配置' : '添加配置'}
                        </Button>
                        {(isAdminPending || isAdminConfirming) && adminHash && (
                          <Alert
                            type="info"
                            message={
                              <span>
                                {isAdminPending ? '等待钱包确认...' : '交易确认中...'}{' '}
                                <a href={`${blockExplorer}/tx/${adminHash}`} target="_blank" rel="noopener noreferrer">查看交易 ↗</a>
                              </span>
                            }
                          />
                        )}
                      </Space>
                    </ProCard>
                  )}

                  {/* 已配置抵押品列表 */}
                  <ProCard title="已配置的抵押品资产">
                    <ProTable<AdminAssetConfig>
                      columns={adminColumns}
                      dataSource={adminAssetConfigList}
                      rowKey="address"
                      search={false}
                      loading={isAdminProcessing}
                      options={{ reload: () => refetchLendingConfig(), density: true }}
                      pagination={{ pageSize: 10, showSizeChanger: true }}
                    />
                  </ProCard>

                  {/* LP 池可用代币 */}
                  <ProCard title="LP 池可用代币（可添加为抵押品）">
                    <Space wrap>
                      {collateralOptions.map((asset) => {
                        const isConfigured = adminAssetConfigsMap.has(asset.address.toLowerCase());
                        return (
                          <Tag
                            key={asset.address}
                            color={isConfigured ? 'green' : 'default'}
                            style={{ margin: 4, fontSize: 14 }}
                          >
                            {asset.symbol || asset.name}
                            {isConfigured && ' ✓'}
                          </Tag>
                        );
                      })}
                    </Space>
                  </ProCard>

                </Space>
              )
            }]}
          />

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