/**
 * LP 管理员配置组件
 * P1-P3 优先级的管理功能
 */

import { useState } from 'react'
import { Button, Checkbox, Input, InputNumber, Select } from 'antd'
import type {
  CooldownForm,
  SwapFeesForm,
  WithdrawForm,
  MaxSwapForm,
  AumAdjustForm,
  LimitsForm,
  PermissionForm,
  VaultConfigForm,
  PriceConfigForm,
  StableTokenConfig,
} from './types'
import type { AvailableToken } from './useLPPoolData'

interface LPAdminConfigProps {
  address: `0x${string}` | undefined
  isProcessing: boolean
  poolPaused?: boolean
  dynamicFees?: boolean
  emergencyMode?: boolean
  swapEnabled?: boolean
  cooldownDuration?: bigint
  usdcPriceSource?: string
  availableTokens: AvailableToken[]
  handleSetCooldownDuration: (form: CooldownForm) => void
  handleSetSwapFees: (form: SwapFeesForm) => void
  handleWithdrawToken: (form: WithdrawForm) => void
  handleSetDynamicFees: (enabled: boolean) => void
  handlePausePool: () => void
  handleUnpausePool: () => void
  handleSetMaxSwapAmount: (form: MaxSwapForm) => void
  handleSetAumAdjustment: (form: AumAdjustForm) => void
  handleSetMaxSwapSlippageBps: (form: LimitsForm) => void
  handleSetMaxPriceChangeBps: (form: LimitsForm) => void
  handleSetPoolManagerGov: (form: PermissionForm) => void
  handleSetVaultGov: (form: PermissionForm) => void
  handleSetHandler: (form: PermissionForm) => void
  handleSetKeeper: (form: PermissionForm) => void
  handleSetSwapper: (form: PermissionForm) => void
  handleSetPoolManager: (form: PermissionForm) => void
  handleSetMinter: (form: PermissionForm) => void
  handleSetWhitelistedToken: (form: VaultConfigForm) => void
  handleClearWhitelistedToken: (token: string) => void
  handleSetEmergencyMode: (enabled: boolean) => void
  handleSetSwapEnabled: (enabled: boolean) => void
  handleSetPrice: (form: PriceConfigForm) => void
  handleSetSpread: (form: PriceConfigForm) => void
  handleSetUsdcPriceSource: (source: string) => void
  handleSetStableToken: (config: StableTokenConfig) => void
  handleAddUsdyVault: (vault: string) => void
  handleRemoveUsdyVault: (vault: string) => void
  show: boolean
  onToggle: () => void
}

// 样式常量
const styles = {
  card: {
    background: '#fff',
    borderRadius: '8px',
    border: '1px solid #e8e8e8',
    marginBottom: '12px',
    overflow: 'hidden',
  },
  cardHeader: {
    padding: '12px 16px',
    background: '#fafafa',
    borderBottom: '1px solid #e8e8e8',
    display: 'flex',
    justifyContent: 'space-between',
    alignItems: 'center',
    cursor: 'pointer',
  },
  cardTitle: {
    fontSize: '13px',
    fontWeight: 600,
    color: '#333',
    margin: 0,
  },
  cardBody: {
    padding: '16px',
  },
  formGroup: {
    marginBottom: '16px',
  },
  formGroupLast: {
    marginBottom: 0,
  },
  label: {
    display: 'block',
    fontSize: '12px',
    fontWeight: 500,
    color: '#666',
    marginBottom: '6px',
  },
  input: {
    width: '100%',
    padding: '8px 12px',
    fontSize: '13px',
    border: '1px solid #d9d9d9',
    borderRadius: '4px',
    outline: 'none',
    transition: 'border-color 0.2s',
  },
  inputSmall: {
    width: '100px',
    padding: '8px 12px',
    fontSize: '13px',
    border: '1px solid #d9d9d9',
    borderRadius: '4px',
  },
  select: {
    width: '100%',
    padding: '8px 12px',
    fontSize: '13px',
    border: '1px solid #d9d9d9',
    borderRadius: '4px',
    background: '#fff',
  },
  row: {
    display: 'flex',
    gap: '12px',
    alignItems: 'flex-end',
  },
  grid2: {
    display: 'grid',
    gridTemplateColumns: '1fr 1fr',
    gap: '12px',
  },
  grid3: {
    display: 'grid',
    gridTemplateColumns: '1fr 1fr 1fr',
    gap: '12px',
  },
  grid4: {
    display: 'grid',
    gridTemplateColumns: '1fr 1fr 1fr 1fr',
    gap: '12px',
  },
  statusBadge: (active: boolean) => ({
    display: 'inline-block',
    padding: '4px 8px',
    fontSize: '11px',
    fontWeight: 600,
    borderRadius: '4px',
    background: active ? '#e6f7e6' : '#fff2f0',
    color: active ? '#52c41a' : '#ff4d4f',
  }),
  hint: {
    fontSize: '11px',
    color: '#999',
    marginTop: '4px',
  },
  warning: {
    fontSize: '11px',
    color: '#ff4d4f',
    marginTop: '4px',
  },
  divider: {
    height: '1px',
    background: '#f0f0f0',
    margin: '16px 0',
  },
  infoBox: {
    padding: '12px',
    background: '#f5f5f5',
    borderRadius: '4px',
    fontSize: '12px',
    color: '#666',
  },
}

export function LPAdminConfig({
  address,
  isProcessing,
  poolPaused,
  dynamicFees,
  emergencyMode,
  swapEnabled,
  cooldownDuration,
  usdcPriceSource,
  availableTokens,
  handleSetCooldownDuration,
  handleSetSwapFees,
  handleWithdrawToken,
  handleSetDynamicFees,
  handlePausePool,
  handleUnpausePool,
  handleSetMaxSwapAmount,
  handleSetAumAdjustment,
  handleSetMaxSwapSlippageBps,
  handleSetMaxPriceChangeBps,
  handleSetPoolManagerGov,
  handleSetVaultGov,
  handleSetHandler,
  handleSetKeeper,
  handleSetSwapper,
  handleSetPoolManager,
  handleSetMinter,
  handleSetWhitelistedToken,
  handleClearWhitelistedToken,
  handleSetEmergencyMode,
  handleSetSwapEnabled,
  handleSetPrice,
  handleSetSpread,
  handleSetUsdcPriceSource,
  handleSetStableToken,
  handleAddUsdyVault,
  handleRemoveUsdyVault,
  show,
  onToggle,
}: LPAdminConfigProps) {

  // 表单状态
  const [cooldownForm, setCooldownForm] = useState<CooldownForm>({
    duration: cooldownDuration ? cooldownDuration.toString() : '3600',
  })
  const [swapFeesForm, setSwapFeesForm] = useState<SwapFeesForm>({
    swapFee: '30',
    stableSwapFee: '4',
    taxBasisPoints: '50',
    stableTaxBasisPoints: '20',
  })
  const [withdrawForm, setWithdrawForm] = useState<WithdrawForm>({
    token: '',
    receiver: '',
    amount: '',
  })
  const [maxSwapForm, setMaxSwapForm] = useState<MaxSwapForm>({
    token: '',
    amount: '',
  })
  const [aumAdjustForm, setAumAdjustForm] = useState<AumAdjustForm>({
    addition: '0',
    deduction: '0',
  })
  const [limitsForm, setLimitsForm] = useState<LimitsForm>({
    maxSwapSlippageBps: '1000',
    maxPriceChangeBps: '500',
  })
  const [permissionForm, setPermissionForm] = useState<PermissionForm>({
    govAddress: '',
    handlerAddress: '',
    handlerActive: true,
    keeperAddress: '',
    keeperActive: true,
    swapperAddress: '',
    swapperActive: true,
    poolManagerAddress: '',
    minterAddress: '',
    minterActive: true,
  })
  const [vaultConfigForm, setVaultConfigForm] = useState<VaultConfigForm>({
    token: '',
    tokenDecimals: '18',
    tokenWeight: '10000',
    maxUsdyAmount: '1000000',
  })
  const [clearWhitelistToken, setClearWhitelistToken] = useState('')
  const [priceConfigForm, setPriceConfigForm] = useState<PriceConfigForm>({
    token: '',
    price: '1',
    spreadBps: '30',
  })
  const [usdcPriceSourceInput, setUsdcPriceSourceInput] = useState('')
  const [stableTokenConfig, setStableTokenConfig] = useState<StableTokenConfig>({
    token: '',
    isStable: true,
  })
  const [vaultToAdd, setVaultToAdd] = useState('')
  const [vaultToRemove, setVaultToRemove] = useState('')

  // 折叠状态
  const [showCoreConfig, setShowCoreConfig] = useState(false)
  const [showTradingLimits, setShowTradingLimits] = useState(false)
  const [showPermissions, setShowPermissions] = useState(false)
  const [showVaultConfig, setShowVaultConfig] = useState(false)
  const [showPriceConfig, setShowPriceConfig] = useState(false)
  const [showUsdyVault, setShowUsdyVault] = useState(false)

  // 可折叠卡片组件
  const Card = ({ title, isOpen, onToggle: toggle, children }: {
    title: string
    isOpen: boolean
    onToggle: () => void
    children: React.ReactNode
  }) => (
    <div style={styles.card}>
      <div style={styles.cardHeader} onClick={toggle}>
        <span style={styles.cardTitle}>{title}</span>
        <span style={{ color: '#999', fontSize: '12px' }}>{isOpen ? '收起' : '展开'}</span>
      </div>
      {isOpen && <div style={styles.cardBody}>{children}</div>}
    </div>
  )

  // 表单项组件
  const FormItem = ({ label, children, last = false }: { label: string; children: React.ReactNode; last?: boolean }) => (
    <div style={last ? styles.formGroupLast : styles.formGroup}>
      <label style={styles.label}>{label}</label>
      {children}
    </div>
  )

  return (
    <div style={{ marginTop: '16px', padding: '12px 16px', background: '#f9f9f9', borderRadius: '8px', border: '1px solid #e0e0e0' }}>
      <div
        style={{ display: 'flex', justifyContent: 'space-between', alignItems: 'center', cursor: 'pointer' }}
        onClick={onToggle}
      >
        <h4 style={{ margin: 0, color: '#333', fontSize: '14px', fontWeight: 600 }}>{'管理员配置'}</h4>
        <span style={{ color: '#999', fontSize: '12px' }}>{show ? '收起' : '展开'}</span>
      </div>

      {show && (
        <div style={{ marginTop: '16px' }}>

          {/* 核心配置 */}
          <Card title={'核心配置'} isOpen={showCoreConfig} onToggle={() => setShowCoreConfig(!showCoreConfig)}>
            <FormItem label={'冷却时间'}>
              <div style={styles.row}>
                <InputNumber style={{ width: '100px' }} value={Number(cooldownForm.duration) || 0} onChange={(v) => setCooldownForm({ duration: String(v ?? 0) })} placeholder="3600" />
                <span style={{ fontSize: '12px', color: '#666' }}>{'秒'}</span>
                <Button
                  type="primary"
                  size="small"
                  onClick={() => handleSetCooldownDuration(cooldownForm)}
                  disabled={isProcessing || !address}
                >
                  {'设置'}
                </Button>
              </div>
              {cooldownDuration !== undefined && (
                <div style={styles.hint}>当前: {cooldownDuration.toString()} 秒</div>
              )}
            </FormItem>

            <div style={styles.divider} />

            <FormItem label={'交换手续费'}>
              <div style={styles.grid2}>
                <div>
                  <div style={{ fontSize: '11px', color: '#999', marginBottom: '4px' }}>swapFee (bps)</div>
                  <InputNumber style={{ width: '100%' }} value={Number(swapFeesForm.swapFee) || 0} onChange={(v) => setSwapFeesForm({ ...swapFeesForm, swapFee: String(v ?? 0) })} placeholder="30" />
                </div>
                <div>
                  <div style={{ fontSize: '11px', color: '#999', marginBottom: '4px' }}>stableSwapFee (bps)</div>
                  <InputNumber style={{ width: '100%' }} value={Number(swapFeesForm.stableSwapFee) || 0} onChange={(v) => setSwapFeesForm({ ...swapFeesForm, stableSwapFee: String(v ?? 0) })} placeholder="4" />
                </div>
                <div>
                  <div style={{ fontSize: '11px', color: '#999', marginBottom: '4px' }}>taxBasisPoints</div>
                  <InputNumber style={{ width: '100%' }} value={Number(swapFeesForm.taxBasisPoints) || 0} onChange={(v) => setSwapFeesForm({ ...swapFeesForm, taxBasisPoints: String(v ?? 0) })} placeholder="50" />
                </div>
                <div>
                  <div style={{ fontSize: '11px', color: '#999', marginBottom: '4px' }}>stableTaxBasisPoints</div>
                  <InputNumber style={{ width: '100%' }} value={Number(swapFeesForm.stableTaxBasisPoints) || 0} onChange={(v) => setSwapFeesForm({ ...swapFeesForm, stableTaxBasisPoints: String(v ?? 0) })} placeholder="20" />
                </div>
              </div>
              <Button
                type="primary"
                size="small"
                onClick={() => handleSetSwapFees(swapFeesForm)}
                disabled={isProcessing || !address}
                style={{ marginTop: '12px' }}
              >
                {'设置手续费'}
              </Button>
            </FormItem>

            <div style={styles.divider} />

            <FormItem label={'提取代币'} last>
              <div style={styles.warning}>{'⚠️ 仅限管理员 - 从池中提取代币'}</div>
              <div style={{ ...styles.grid3, marginTop: '8px' }}>
                <Select
                  value={withdrawForm.token || undefined}
                  onChange={(v) => setWithdrawForm({ ...withdrawForm, token: v || '' })}
                  style={{ width: '100%' }}
                  placeholder={'选择代币'}
                  options={availableTokens.map(token => ({ value: token.address, label: token.symbol }))}
                />
                <Input
                  value={withdrawForm.receiver}
                  onChange={(e) => setWithdrawForm({ ...withdrawForm, receiver: e.target.value })}
                  placeholder={'接收地址'}
                />
                <Input
                  value={withdrawForm.amount}
                  onChange={(e) => setWithdrawForm({ ...withdrawForm, amount: e.target.value })}
                  placeholder={'数量'}
                />
              </div>
              <Button
                danger
                size="small"
                onClick={() => handleWithdrawToken(withdrawForm)}
                disabled={isProcessing || !address || !withdrawForm.token || !withdrawForm.receiver || !withdrawForm.amount}
                style={{ marginTop: '12px' }}
              >
                {'提取'}
              </Button>
            </FormItem>
          </Card>

          {/* 交易限制 */}
          <Card title={'交易限制'} isOpen={showTradingLimits} onToggle={() => setShowTradingLimits(!showTradingLimits)}>
            <div style={styles.grid2}>
              <div style={{ padding: '12px', background: '#fafafa', borderRadius: '6px' }}>
                <div style={{ fontSize: '12px', color: '#666', marginBottom: '8px' }}>{'动态手续费'}</div>
                <div style={styles.row}>
                  <span style={styles.statusBadge(!!dynamicFees)}>{dynamicFees ? 'ON' : 'OFF'}</span>
                  <Button
                    size="small"
                    type={dynamicFees ? undefined : 'primary'}
                    onClick={() => handleSetDynamicFees(!dynamicFees)}
                    disabled={isProcessing || !address}
                  >
                    {dynamicFees ? '关闭' : '开启'}
                  </Button>
                </div>
              </div>
              <div style={{ padding: '12px', background: '#fafafa', borderRadius: '6px' }}>
                <div style={{ fontSize: '12px', color: '#666', marginBottom: '8px' }}>{'池子状态'}</div>
                <div style={styles.row}>
                  <span style={styles.statusBadge(!poolPaused)}>{poolPaused ? '已暂停' : '运行中'}</span>
                  <Button
                    size="small"
                    type={poolPaused ? 'primary' : undefined}
                    onClick={poolPaused ? handleUnpausePool : handlePausePool}
                    disabled={isProcessing || !address}
                  >
                    {poolPaused ? '恢复池子' : '暂停池子'}
                  </Button>
                </div>
              </div>
            </div>

            <div style={styles.divider} />

            <FormItem label={'最大交换数量'}>
              <div style={styles.row}>
                <Select
                  value={maxSwapForm.token || undefined}
                  onChange={(v) => setMaxSwapForm({ ...maxSwapForm, token: v || '' })}
                  style={{ width: '140px' }}
                  placeholder={'选择代币'}
                  options={availableTokens.map(token => ({ value: token.address, label: token.symbol }))}
                />
                <div style={{ width: '140px' }}>
                  <Input
                    value={maxSwapForm.amount}
                    onChange={(e) => setMaxSwapForm({ ...maxSwapForm, amount: e.target.value })}
                    placeholder={'数量'}
                  />
                </div>
                <Button
                  type="primary"
                  size="small"
                  onClick={() => handleSetMaxSwapAmount(maxSwapForm)}
                  disabled={isProcessing || !address || !maxSwapForm.token || !maxSwapForm.amount}
                >
                  {'设置'}
                </Button>
              </div>
            </FormItem>

            <FormItem label={'AUM 调整'}>
              <div style={styles.row}>
                <div>
                  <div style={{ fontSize: '11px', color: '#999', marginBottom: '4px' }}>{'增加'}</div>
                  <InputNumber style={{ width: '100px' }} value={Number(aumAdjustForm.addition) || 0} onChange={(v) => setAumAdjustForm({ ...aumAdjustForm, addition: String(v ?? 0) })} placeholder="0" />
                </div>
                <div>
                  <div style={{ fontSize: '11px', color: '#999', marginBottom: '4px' }}>{'减少'}</div>
                  <InputNumber style={{ width: '100px' }} value={Number(aumAdjustForm.deduction) || 0} onChange={(v) => setAumAdjustForm({ ...aumAdjustForm, deduction: String(v ?? 0) })} placeholder="0" />
                </div>
                <Button
                  type="primary"
                  size="small"
                  onClick={() => handleSetAumAdjustment(aumAdjustForm)}
                  disabled={isProcessing || !address}
                  style={{ alignSelf: 'flex-end' }}
                >
                  {'设置'}
                </Button>
              </div>
            </FormItem>

            <FormItem label={`${'最大滑点'} / ${'最大价格变动'}`} last>
              <div style={styles.row}>
                <div>
                  <div style={{ fontSize: '11px', color: '#999', marginBottom: '4px' }}>{'最大滑点'} (bps)</div>
                  <InputNumber style={{ width: '100px' }} value={Number(limitsForm.maxSwapSlippageBps) || 0} onChange={(v) => setLimitsForm({ ...limitsForm, maxSwapSlippageBps: String(v ?? 0) })} placeholder="1000" />
                </div>
                <div>
                  <div style={{ fontSize: '11px', color: '#999', marginBottom: '4px' }}>{'最大价格变动'} (bps)</div>
                  <InputNumber style={{ width: '100px' }} value={Number(limitsForm.maxPriceChangeBps) || 0} onChange={(v) => setLimitsForm({ ...limitsForm, maxPriceChangeBps: String(v ?? 0) })} placeholder="500" />
                </div>
                <Button
                  size="small"
                  onClick={() => handleSetMaxSwapSlippageBps(limitsForm)}
                  disabled={isProcessing || !address}
                  style={{ alignSelf: 'flex-end' }}
                >
                  Slippage
                </Button>
                <Button
                  size="small"
                  onClick={() => handleSetMaxPriceChangeBps(limitsForm)}
                  disabled={isProcessing || !address}
                  style={{ alignSelf: 'flex-end' }}
                >
                  Price
                </Button>
              </div>
            </FormItem>
          </Card>

          {/* 权限管理 */}
          <Card title={'权限管理'} isOpen={showPermissions} onToggle={() => setShowPermissions(!showPermissions)}>
            <FormItem label={'设置 Gov'}>
              <div style={{ display: 'flex', gap: 8 }}>
                <Input
                  value={permissionForm.govAddress}
                  onChange={(e) => setPermissionForm({ ...permissionForm, govAddress: e.target.value })}
                  placeholder="0x..."
                />
                <Button
                  size="small"
                  onClick={() => handleSetPoolManagerGov(permissionForm)}
                  disabled={isProcessing || !address || !permissionForm.govAddress}
                >
                  PoolManager
                </Button>
                <Button
                  size="small"
                  onClick={() => handleSetVaultGov(permissionForm)}
                  disabled={isProcessing || !address || !permissionForm.govAddress}
                >
                  Vault
                </Button>
              </div>
            </FormItem>

            <FormItem label={'设置 Handler'}>
              <div style={styles.row}>
                <div style={{ flex: 1 }}>
                  <Input
                    value={permissionForm.handlerAddress}
                    onChange={(e) => setPermissionForm({ ...permissionForm, handlerAddress: e.target.value })}
                    placeholder="0x..."
                  />
                </div>
                <label style={{ fontSize: '12px', display: 'flex', alignItems: 'center', gap: '4px' }}>
                  <Checkbox
                    checked={permissionForm.handlerActive}
                    onChange={(e) => setPermissionForm({ ...permissionForm, handlerActive: e.target.checked })}
                  />
                  {'是否激活'}
                </label>
                <Button
                  type="primary"
                  size="small"
                  onClick={() => handleSetHandler(permissionForm)}
                  disabled={isProcessing || !address || !permissionForm.handlerAddress}
                >
                  {'设置'}
                </Button>
              </div>
            </FormItem>

            <FormItem label={'设置 Keeper'}>
              <div style={styles.row}>
                <div style={{ flex: 1 }}>
                  <Input
                    value={permissionForm.keeperAddress}
                    onChange={(e) => setPermissionForm({ ...permissionForm, keeperAddress: e.target.value })}
                    placeholder="0x..."
                  />
                </div>
                <label style={{ fontSize: '12px', display: 'flex', alignItems: 'center', gap: '4px' }}>
                  <Checkbox
                    checked={permissionForm.keeperActive}
                    onChange={(e) => setPermissionForm({ ...permissionForm, keeperActive: e.target.checked })}
                  />
                  {'是否激活'}
                </label>
                <Button
                  type="primary"
                  size="small"
                  onClick={() => handleSetKeeper(permissionForm)}
                  disabled={isProcessing || !address || !permissionForm.keeperAddress}
                >
                  {'设置'}
                </Button>
              </div>
            </FormItem>

            <FormItem label={'设置 Swapper'}>
              <div style={styles.row}>
                <div style={{ flex: 1 }}>
                  <Input
                    value={permissionForm.swapperAddress}
                    onChange={(e) => setPermissionForm({ ...permissionForm, swapperAddress: e.target.value })}
                    placeholder="0x..."
                  />
                </div>
                <label style={{ fontSize: '12px', display: 'flex', alignItems: 'center', gap: '4px' }}>
                  <Checkbox
                    checked={permissionForm.swapperActive}
                    onChange={(e) => setPermissionForm({ ...permissionForm, swapperActive: e.target.checked })}
                  />
                  {'是否激活'}
                </label>
                <Button
                  type="primary"
                  size="small"
                  onClick={() => handleSetSwapper(permissionForm)}
                  disabled={isProcessing || !address || !permissionForm.swapperAddress}
                >
                  {'设置'}
                </Button>
              </div>
            </FormItem>

            <FormItem label={'设置 PoolManager'}>
              <div style={{ display: 'flex', gap: 8 }}>
                <Input
                  value={permissionForm.poolManagerAddress}
                  onChange={(e) => setPermissionForm({ ...permissionForm, poolManagerAddress: e.target.value })}
                  placeholder="0x..."
                />
                <Button
                  type="primary"
                  size="small"
                  onClick={() => handleSetPoolManager(permissionForm)}
                  disabled={isProcessing || !address || !permissionForm.poolManagerAddress}
                >
                  {'设置'}
                </Button>
              </div>
            </FormItem>

            <FormItem label="Minter (ytLP)" last>
              <div style={styles.row}>
                <div style={{ flex: 1 }}>
                  <Input
                    value={permissionForm.minterAddress}
                    onChange={(e) => setPermissionForm({ ...permissionForm, minterAddress: e.target.value })}
                    placeholder="0x..."
                  />
                </div>
                <label style={{ fontSize: '12px', display: 'flex', alignItems: 'center', gap: '4px' }}>
                  <Checkbox
                    checked={permissionForm.minterActive}
                    onChange={(e) => setPermissionForm({ ...permissionForm, minterActive: e.target.checked })}
                  />
                  {'是否激活'}
                </label>
                <Button
                  type="primary"
                  size="small"
                  onClick={() => handleSetMinter(permissionForm)}
                  disabled={isProcessing || !address || !permissionForm.minterAddress}
                >
                  {'设置'}
                </Button>
              </div>
            </FormItem>
          </Card>

          {/* YTVault 配置 */}
          <Card title="YTVault 配置" isOpen={showVaultConfig} onToggle={() => setShowVaultConfig(!showVaultConfig)}>
            <div style={styles.grid2}>
              <div style={{ padding: '12px', background: '#fafafa', borderRadius: '6px' }}>
                <div style={{ fontSize: '12px', color: '#666', marginBottom: '8px' }}>紧急模式</div>
                <div style={styles.row}>
                  <span style={styles.statusBadge(!emergencyMode)}>{emergencyMode ? 'ON' : '正常'}</span>
                  <Button
                    type={emergencyMode ? 'primary' : undefined}
                    danger={!emergencyMode}
                    size="small"
                    onClick={() => handleSetEmergencyMode(!emergencyMode)}
                    disabled={isProcessing || !address}
                  >
                    {emergencyMode ? '关闭' : '开启'}
                  </Button>
                </div>
              </div>
              <div style={{ padding: '12px', background: '#fafafa', borderRadius: '6px' }}>
                <div style={{ fontSize: '12px', color: '#666', marginBottom: '8px' }}>Swap 开关</div>
                <div style={styles.row}>
                  <span style={styles.statusBadge(!!swapEnabled)}>{swapEnabled ? '开启' : '关闭'}</span>
                  <Button
                    type={swapEnabled ? undefined : 'primary'}
                    danger={!!swapEnabled}
                    size="small"
                    onClick={() => handleSetSwapEnabled(!swapEnabled)}
                    disabled={isProcessing || !address}
                  >
                    {swapEnabled ? '关闭' : '开启'}
                  </Button>
                </div>
              </div>
            </div>

            <div style={styles.divider} />

            <FormItem label="添加/更新白名单代币">
              <div style={styles.grid4}>
                <div>
                  <div style={{ fontSize: '11px', color: '#999', marginBottom: '4px' }}>代币</div>
                  <Select
                    value={availableTokens.some(t => t.address.toLowerCase() === vaultConfigForm.token.toLowerCase()) ? vaultConfigForm.token : undefined}
                    onChange={(v) => setVaultConfigForm({ ...vaultConfigForm, token: v || '' })}
                    style={{ width: '100%' }}
                    placeholder="选择或输入"
                    options={availableTokens.map(token => ({ value: token.address, label: token.symbol }))}
                  />
                </div>
                <div>
                  <div style={{ fontSize: '11px', color: '#999', marginBottom: '4px' }}>Decimals</div>
                  <InputNumber style={{ width: '100%' }} value={Number(vaultConfigForm.tokenDecimals) || 0} onChange={(v) => setVaultConfigForm({ ...vaultConfigForm, tokenDecimals: String(v ?? 0) })} placeholder="18" />
                </div>
                <div>
                  <div style={{ fontSize: '11px', color: '#999', marginBottom: '4px' }}>Weight</div>
                  <InputNumber style={{ width: '100%' }} value={Number(vaultConfigForm.tokenWeight) || 0} onChange={(v) => setVaultConfigForm({ ...vaultConfigForm, tokenWeight: String(v ?? 0) })} placeholder="10000" />
                </div>
                <div>
                  <div style={{ fontSize: '11px', color: '#999', marginBottom: '4px' }}>Max USDY</div>
                  <InputNumber style={{ width: '100%' }} value={Number(vaultConfigForm.maxUsdyAmount) || 0} onChange={(v) => setVaultConfigForm({ ...vaultConfigForm, maxUsdyAmount: String(v ?? 0) })} placeholder="1000000" />
                </div>
              </div>
              <Input
                value={vaultConfigForm.token}
                onChange={(e) => setVaultConfigForm({ ...vaultConfigForm, token: e.target.value })}
                placeholder="或手动输入代币地址: 0x..."
                style={{ marginTop: '8px' }}
              />
              <Button
                type="primary"
                size="small"
                onClick={() => handleSetWhitelistedToken(vaultConfigForm)}
                disabled={isProcessing || !address || !vaultConfigForm.token}
                style={{ marginTop: '12px' }}
              >
                添加/更新白名单
              </Button>
            </FormItem>

            <FormItem label="移除白名单代币" last>
              <div style={styles.row}>
                <Select
                  value={clearWhitelistToken || undefined}
                  onChange={(v) => setClearWhitelistToken(v || '')}
                  style={{ width: '100%' }}
                  placeholder="选择代币"
                  options={availableTokens.filter(t => t.isWhitelisted).map(token => ({ value: token.address, label: token.symbol }))}
                />
                <Button
                  size="small"
                  onClick={() => handleClearWhitelistedToken(clearWhitelistToken)}
                  disabled={isProcessing || !address || !clearWhitelistToken}
                >
                  移除
                </Button>
              </div>
            </FormItem>
          </Card>

          {/* 价格配置 */}
          <Card title="价格配置 (YTPriceFeed)" isOpen={showPriceConfig} onToggle={() => setShowPriceConfig(!showPriceConfig)}>
            <FormItem label="USDC 价格源 (Chainlink)">
              <div style={{ display: 'flex', gap: 8 }}>
                <Input
                  value={usdcPriceSourceInput}
                  onChange={(e) => setUsdcPriceSourceInput(e.target.value)}
                  placeholder="0x..."
                />
                <Button
                  size="small"
                  onClick={() => handleSetUsdcPriceSource(usdcPriceSourceInput)}
                  disabled={isProcessing || !address || !usdcPriceSourceInput}
                >
                  设置
                </Button>
              </div>
              <div style={styles.hint}>当前: {usdcPriceSource || '未设置'}</div>
            </FormItem>

            <FormItem label="设置代币价格">
              <div style={styles.grid3}>
                <div>
                  <div style={{ fontSize: '11px', color: '#999', marginBottom: '4px' }}>代币</div>
                  <Select
                    value={priceConfigForm.token || undefined}
                    onChange={(v) => setPriceConfigForm({ ...priceConfigForm, token: v || '' })}
                    style={{ width: '100%' }}
                    placeholder="选择代币"
                    options={availableTokens.map(token => ({ value: token.address, label: token.symbol }))}
                  />
                </div>
                <div>
                  <div style={{ fontSize: '11px', color: '#999', marginBottom: '4px' }}>价格</div>
                  <Input
                    value={priceConfigForm.price}
                    onChange={(e) => setPriceConfigForm({ ...priceConfigForm, price: e.target.value })}
                    placeholder="1"
                  />
                </div>
                <div>
                  <div style={{ fontSize: '11px', color: '#999', marginBottom: '4px' }}>价差 (bps)</div>
                  <InputNumber style={{ width: '100%' }} value={Number(priceConfigForm.spreadBps) || 0} onChange={(v) => setPriceConfigForm({ ...priceConfigForm, spreadBps: String(v ?? 0) })} placeholder="30" />
                </div>
              </div>
              <div style={{ ...styles.row, marginTop: '12px' }}>
                <Button
                  type="primary"
                  size="small"
                  onClick={() => handleSetPrice(priceConfigForm)}
                  disabled={isProcessing || !address || !priceConfigForm.token || !priceConfigForm.price}
                >
                  设置价格
                </Button>
                <Button
                  size="small"
                  onClick={() => handleSetSpread(priceConfigForm)}
                  disabled={isProcessing || !address || !priceConfigForm.token || !priceConfigForm.spreadBps}
                >
                  设置价差
                </Button>
              </div>
            </FormItem>

            <FormItem label="设置稳定币标记" last>
              <div style={styles.row}>
                <Select
                  value={stableTokenConfig.token || undefined}
                  onChange={(v) => setStableTokenConfig({ ...stableTokenConfig, token: v || '' })}
                  style={{ width: '100%' }}
                  placeholder="选择代币"
                  options={availableTokens.map(token => ({ value: token.address, label: token.symbol }))}
                />
                <label style={{ fontSize: '12px', display: 'flex', alignItems: 'center', gap: '4px' }}>
                  <Checkbox
                    checked={stableTokenConfig.isStable}
                    onChange={(e) => setStableTokenConfig({ ...stableTokenConfig, isStable: e.target.checked })}
                  />
                  是稳定币
                </label>
                <Button
                  type="primary"
                  size="small"
                  onClick={() => handleSetStableToken(stableTokenConfig)}
                  disabled={isProcessing || !address || !stableTokenConfig.token}
                >
                  设置
                </Button>
              </div>
            </FormItem>
          </Card>

          {/* USDY Vault 白名单 */}
          <Card title="USDY Vault 白名单" isOpen={showUsdyVault} onToggle={() => setShowUsdyVault(!showUsdyVault)}>
            <div style={styles.hint}>管理可以 mint/burn USDY 的 Vault 地址</div>

            <FormItem label="添加 Vault">
              <div style={{ display: 'flex', gap: 8 }}>
                <Input
                  value={vaultToAdd}
                  onChange={(e) => setVaultToAdd(e.target.value)}
                  placeholder="0x..."
                />
                <Button
                  type="primary"
                  size="small"
                  onClick={() => handleAddUsdyVault(vaultToAdd)}
                  disabled={isProcessing || !address || !vaultToAdd}
                >
                  添加
                </Button>
              </div>
            </FormItem>

            <FormItem label="移除 Vault" last>
              <div style={{ display: 'flex', gap: 8 }}>
                <Input
                  value={vaultToRemove}
                  onChange={(e) => setVaultToRemove(e.target.value)}
                  placeholder="0x..."
                />
                <Button
                  danger
                  size="small"
                  onClick={() => handleRemoveUsdyVault(vaultToRemove)}
                  disabled={isProcessing || !address || !vaultToRemove}
                >
                  移除
                </Button>
              </div>
            </FormItem>
          </Card>

          {/* 配置提示 */}
          <div style={styles.infoBox}>
            <strong>配置步骤:</strong> 1. 设置价格 - 2. 设置价差(可选) - 3. 添加白名单
          </div>
        </div>
      )}
    </div>
  )
}
