import { useState, useEffect, useMemo } from 'react';
import { useIntl } from '@umijs/max';
import { PageContainer, ProCard, ProForm, ProFormText, ProFormDigit, StatisticCard, ProTable } from '@ant-design/pro-components';
import type { ProColumns } from '@ant-design/pro-components';
import { Button, Space, Typography, Tag, message, Row, Col, Select, Input, DatePicker, Form, Checkbox, Alert, Descriptions, Tooltip, Badge, Collapse } from 'antd';
import dayjs from 'dayjs';
import { PlusOutlined, PauseCircleOutlined, PlayCircleOutlined, EditOutlined, SettingOutlined, ThunderboltOutlined, SafetyOutlined, CopyOutlined } from '@ant-design/icons';
import { useAccount, useReadContract, useReadContracts, useWriteContract, useWaitForTransactionReceipt, useChainId } from 'wagmi';
import { parseUnits, formatUnits } from 'viem';
import { GAS_CONFIG, FACTORY_ABI, VAULT_ABI, getContracts, getDecimals, getChainName, getBlockExplorer } from '@/config/contracts';

const { Text, Link } = Typography;

interface VaultInfo {
  address: string;
  symbol: string;
  paused: boolean;
}

export default function FactoryPage() {
  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 [showCreateForm, setShowCreateForm] = useState(false);
  const [selectedVault, setSelectedVault] = useState<string | null>(null);

  // Owner 配置 state
  const [newDefaultHardCap, setNewDefaultHardCap] = useState('');
  const [selectedVaultForManage, setSelectedVaultForManage] = useState<string>('');
  const [singleVaultYtPrice, setSingleVaultYtPrice] = useState('1');
  const [singleVaultHardCap, setSingleVaultHardCap] = useState('');
  const [singleVaultRedemptionTime, setSingleVaultRedemptionTime] = useState('');
  const [singleVaultManager, setSingleVaultManager] = useState('');

  // 权限测试 state
  const [runningTest, setRunningTest] = useState<string | null>(null);

  // 批量操作 state
  const [batchYtPrice, setBatchYtPrice] = useState('1');
  const [batchHardCap, setBatchHardCap] = useState('');
  const [batchRedemptionTime, setBatchRedemptionTime] = useState('');
  const [selectedVaultsForBatch, setSelectedVaultsForBatch] = useState<string[]>([]);

  // 批量创建 state
  const [showBatchCreate, setShowBatchCreate] = useState(false);
  const [batchCreateVaults, setBatchCreateVaults] = useState<{
    name: string; symbol: string; manager: string; hardCap: string; redemptionTime: string; ytPrice: string;
  }[]>([{ name: '', symbol: '', manager: '', hardCap: '100000', redemptionTime: '', ytPrice: '1' }]);

  // 高级功能 state
  const [showAdvanced, setShowAdvanced] = useState(false);
  const [newImplementation, setNewImplementation] = useState('');
  const [upgradeVaultAddr, setUpgradeVaultAddr] = useState('');
  const [upgradeImplAddr, setUpgradeImplAddr] = useState('');
  const [checkVaultAddr, setCheckVaultAddr] = useState('');

  // 读取工厂信息
  const { data: allVaults, refetch: refetchVaults } = useReadContract({
    address: CONTRACTS.FACTORY,
    abi: FACTORY_ABI,
    functionName: 'getAllVaults',
  });

  const { data: vaultCount } = useReadContract({
    address: CONTRACTS.FACTORY,
    abi: FACTORY_ABI,
    functionName: 'getVaultCount',
  });

  const { data: owner } = useReadContract({
    address: CONTRACTS.FACTORY,
    abi: FACTORY_ABI,
    functionName: 'owner',
  });

  const { data: defaultHardCap } = useReadContract({
    address: CONTRACTS.FACTORY,
    abi: FACTORY_ABI,
    functionName: 'defaultHardCap',
  });

  const { data: vaultImplementation } = useReadContract({
    address: CONTRACTS.FACTORY,
    abi: FACTORY_ABI,
    functionName: 'vaultImplementation',
  });

  const { data: isValidVault } = useReadContract({
    address: CONTRACTS.FACTORY,
    abi: FACTORY_ABI,
    functionName: 'isVault',
    args: checkVaultAddr && checkVaultAddr.startsWith('0x') && checkVaultAddr.length === 42
      ? [checkVaultAddr as `0x${string}`]
      : undefined,
  });

  // 批量读取金库 symbols 和 paused 状态
  const vaultSymbolContracts = useMemo(() => {
    if (!allVaults || allVaults.length === 0) return [];
    return allVaults.map((addr: string) => ({
      address: addr as `0x${string}`,
      abi: VAULT_ABI,
      functionName: 'symbol' as const,
    }));
  }, [allVaults]);

  const pausedContracts = useMemo(() => {
    if (!allVaults || allVaults.length === 0) return [];
    return allVaults.map((addr: string) => ({
      address: addr as `0x${string}`,
      abi: VAULT_ABI,
      functionName: 'paused' as const,
    }));
  }, [allVaults]);

  const { data: vaultSymbolsData } = useReadContracts({ contracts: vaultSymbolContracts });
  const { data: pausedResults, refetch: refetchPaused } = useReadContracts({ contracts: pausedContracts });

  // 构建金库列表数据
  const vaultTableData: VaultInfo[] = useMemo(() => {
    if (!allVaults) return [];
    return allVaults.map((addr: string, index: number) => {
      const symbolResult = vaultSymbolsData?.[index];
      const pausedResult = pausedResults?.[index];
      return {
        address: addr,
        symbol: symbolResult?.status === 'success' ? symbolResult.result as string : `Vault ${index + 1}`,
        paused: pausedResult?.status === 'success' ? pausedResult.result as boolean : false,
      };
    });
  }, [allVaults, vaultSymbolsData, pausedResults]);

  const isOwner = !!(address && owner && (address as string).toLowerCase() === (owner as string).toLowerCase());

  const copyToClipboard = (text: string) => {
    navigator.clipboard.writeText(text);
    message.success('已复制');
  };

  const runPermissionTest = (testType: string) => {
    const testVault = allVaults && allVaults.length > 0 ? allVaults[0] : undefined;
    if (!testVault) { message.warning('没有可用的金库地址'); return; }
    setRunningTest(testType);
    try {
      if (testType === 'update_price_not_owner') {
        writeContract({
          address: CONTRACTS.FACTORY,
          abi: FACTORY_ABI,
          functionName: 'updateVaultPrices',
          args: [testVault as `0x${string}`, parseUnits('1', TOKEN_DECIMALS.INTERNAL_PRICE)],
          gas: GAS_CONFIG.STANDARD,
        });
      } else if (testType === 'set_manager_not_owner') {
        writeContract({
          address: CONTRACTS.FACTORY,
          abi: FACTORY_ABI,
          functionName: 'setVaultManager',
          args: [testVault as `0x${string}`, address as `0x${string}`],
          gas: GAS_CONFIG.STANDARD,
        });
      }
    } catch (err) {
      console.error('Permission test error:', err);
    }
  };

  const { writeContract, data: hash, isPending, reset, error: writeError } = useWriteContract();
  const { isLoading: isConfirming, isSuccess } = useWaitForTransactionReceipt({ hash });

  useEffect(() => {
    if (isSuccess) {
      message.success(intl.formatMessage({ id: 'pages.toast.txSuccess' }));
      refetchVaults();
      refetchPaused();
      reset();
      setShowCreateForm(false);
      setRunningTest(null);
    }
  }, [isSuccess]);

  useEffect(() => {
    if (writeError) {
      const errorMsg = typeof writeError === 'string' ? writeError : writeError.message || 'Transaction failed';
      message.error(errorMsg);
      reset();
      setRunningTest(null);
    }
  }, [writeError]);

  const isProcessing = isPending || isConfirming;

  // ===== 创建金库 =====
  const handleCreateVault = async (values: any) => {
    const redemptionDate = new Date(values.redemptionTime);
    const redemptionTimestamp = isNaN(redemptionDate.getTime())
      ? BigInt(values.redemptionTime || 86400)
      : BigInt(Math.floor(redemptionDate.getTime() / 1000));
    writeContract({
      address: CONTRACTS.FACTORY,
      abi: FACTORY_ABI,
      functionName: 'createVault',
      args: [
        values.name,
        values.symbol,
        values.manager as `0x${string}`,
        parseUnits(values.hardCap || defaultHardCap?.toString() || '100000', TOKEN_DECIMALS.YT),
        CONTRACTS.USDC,
        redemptionTimestamp,
        parseUnits(values.initialYtPrice || '1', TOKEN_DECIMALS.INTERNAL_PRICE),
        CONTRACTS.USDC_PRICE_FEED,
      ],
      gas: GAS_CONFIG.VERY_COMPLEX,
    });
  };

  // ===== 单金库操作（表格行） =====
  const handleUpdatePrice = async (vaultAddr: string, values: any) => {
    writeContract({
      address: CONTRACTS.FACTORY,
      abi: FACTORY_ABI,
      functionName: 'updateVaultPrices',
      args: [vaultAddr as `0x${string}`, parseUnits(values.ytPrice, TOKEN_DECIMALS.INTERNAL_PRICE)],
      gas: GAS_CONFIG.STANDARD,
    });
  };

  const handleUpdateHardCap = async (vaultAddr: string, values: any) => {
    writeContract({
      address: vaultAddr as `0x${string}`,
      abi: VAULT_ABI,
      functionName: 'setHardCap',
      args: [parseUnits(values.hardCap, TOKEN_DECIMALS.YT)],
      gas: GAS_CONFIG.STANDARD,
    });
  };

  const handleTogglePause = (vaultAddr: string, currentlyPaused: boolean) => {
    writeContract({
      address: CONTRACTS.FACTORY,
      abi: FACTORY_ABI,
      functionName: currentlyPaused ? 'unpauseVault' : 'pauseVault',
      args: [vaultAddr as `0x${string}`],
      gas: GAS_CONFIG.STANDARD,
    });
  };

  // ===== Owner 配置 - 单金库管理 =====
  const handleUpdateSingleVaultYTPrice = () => {
    if (!selectedVaultForManage || !singleVaultYtPrice) return;
    writeContract({
      address: CONTRACTS.FACTORY,
      abi: FACTORY_ABI,
      functionName: 'updateVaultPrices',
      args: [selectedVaultForManage as `0x${string}`, parseUnits(singleVaultYtPrice, TOKEN_DECIMALS.INTERNAL_PRICE)],
      gas: GAS_CONFIG.STANDARD,
    });
  };

  const handleSetSingleVaultHardCap = () => {
    if (!selectedVaultForManage || !singleVaultHardCap) return;
    writeContract({
      address: CONTRACTS.FACTORY,
      abi: FACTORY_ABI,
      functionName: 'setHardCap',
      args: [selectedVaultForManage as `0x${string}`, parseUnits(singleVaultHardCap, TOKEN_DECIMALS.YT)],
      gas: GAS_CONFIG.STANDARD,
    });
  };

  const handleSetSingleVaultRedemptionTime = () => {
    if (!selectedVaultForManage || !singleVaultRedemptionTime) return;
    const timestamp = BigInt(Math.floor(new Date(singleVaultRedemptionTime).getTime() / 1000));
    writeContract({
      address: CONTRACTS.FACTORY,
      abi: FACTORY_ABI,
      functionName: 'setVaultNextRedemptionTime',
      args: [selectedVaultForManage as `0x${string}`, timestamp],
      gas: GAS_CONFIG.STANDARD,
    });
  };

  const handleSetSingleVaultManager = () => {
    if (!selectedVaultForManage || !singleVaultManager) return;
    writeContract({
      address: CONTRACTS.FACTORY,
      abi: FACTORY_ABI,
      functionName: 'setVaultManager',
      args: [selectedVaultForManage as `0x${string}`, singleVaultManager as `0x${string}`],
      gas: GAS_CONFIG.STANDARD,
    });
  };

  const handleSetDefaultHardCap = () => {
    if (!newDefaultHardCap) return;
    writeContract({
      address: CONTRACTS.FACTORY,
      abi: FACTORY_ABI,
      functionName: 'setDefaultHardCap',
      args: [parseUnits(newDefaultHardCap, TOKEN_DECIMALS.YT)],
      gas: GAS_CONFIG.STANDARD,
    });
  };

  // ===== 批量暂停/恢复 =====
  const handleBatchPauseVaults = () => {
    if (selectedVaultsForBatch.length === 0) return;
    writeContract({
      address: CONTRACTS.FACTORY,
      abi: FACTORY_ABI,
      functionName: 'pauseVaultBatch',
      args: [selectedVaultsForBatch as `0x${string}`[]],
      gas: GAS_CONFIG.VERY_COMPLEX,
    });
  };

  const handleBatchUnpauseVaults = () => {
    if (selectedVaultsForBatch.length === 0) return;
    writeContract({
      address: CONTRACTS.FACTORY,
      abi: FACTORY_ABI,
      functionName: 'unpauseVaultBatch',
      args: [selectedVaultsForBatch as `0x${string}`[]],
      gas: GAS_CONFIG.VERY_COMPLEX,
    });
  };

  // ===== 批量设置赎回时间 =====
  const handleBatchSetRedemptionTime = () => {
    if (selectedVaultsForBatch.length === 0 || !batchRedemptionTime) return;
    const timestamp = BigInt(Math.floor(new Date(batchRedemptionTime).getTime() / 1000));
    writeContract({
      address: CONTRACTS.FACTORY,
      abi: FACTORY_ABI,
      functionName: 'setVaultNextRedemptionTimeBatch',
      args: [selectedVaultsForBatch as `0x${string}`[], timestamp],
      gas: GAS_CONFIG.VERY_COMPLEX,
    });
  };

  // ===== 批量创建金库 =====
  const addBatchCreateRow = () => {
    setBatchCreateVaults([...batchCreateVaults, { name: '', symbol: '', manager: '', hardCap: '100000', redemptionTime: '', ytPrice: '1' }]);
  };

  const removeBatchCreateRow = (index: number) => {
    if (batchCreateVaults.length > 1) {
      setBatchCreateVaults(batchCreateVaults.filter((_, i) => i !== index));
    }
  };

  const updateBatchCreateRow = (index: number, field: string, value: string) => {
    const updated = [...batchCreateVaults];
    updated[index] = { ...updated[index], [field]: value };
    setBatchCreateVaults(updated);
  };

  const handleBatchCreateVaults = () => {
    const validVaults = batchCreateVaults.filter(v => v.name && v.symbol && v.manager && v.hardCap && v.redemptionTime);
    if (validVaults.length === 0) return;
    const names = validVaults.map(v => v.name);
    const symbols = validVaults.map(v => v.symbol);
    const managers = validVaults.map(v => v.manager as `0x${string}`);
    const hardCaps = validVaults.map(v => parseUnits(v.hardCap, TOKEN_DECIMALS.YT));
    const redemptionTimes = validVaults.map(v => BigInt(Math.floor(new Date(v.redemptionTime).getTime() / 1000)));
    const ytPrices = validVaults.map(v => parseUnits(v.ytPrice || '1', TOKEN_DECIMALS.INTERNAL_PRICE));
    writeContract({
      address: CONTRACTS.FACTORY,
      abi: FACTORY_ABI,
      functionName: 'createVaultBatch',
      args: [names, symbols, managers, hardCaps, CONTRACTS.USDC, redemptionTimes, ytPrices, CONTRACTS.USDC_PRICE_FEED],
      gas: GAS_CONFIG.VERY_COMPLEX,
    });
  };

  // ===== 高级功能 =====
  const handleSetVaultImplementation = () => {
    if (!newImplementation) return;
    writeContract({
      address: CONTRACTS.FACTORY,
      abi: FACTORY_ABI,
      functionName: 'setVaultImplementation',
      args: [newImplementation as `0x${string}`],
      gas: GAS_CONFIG.STANDARD,
    });
  };

  const handleUpgradeVault = () => {
    if (!upgradeVaultAddr || !upgradeImplAddr) return;
    writeContract({
      address: CONTRACTS.FACTORY,
      abi: FACTORY_ABI,
      functionName: 'upgradeVault',
      args: [upgradeVaultAddr as `0x${string}`, upgradeImplAddr as `0x${string}`],
      gas: GAS_CONFIG.COMPLEX,
    });
  };

  const handleBatchUpgradeVault = () => {
    if (selectedVaultsForBatch.length === 0 || !upgradeImplAddr) return;
    writeContract({
      address: CONTRACTS.FACTORY,
      abi: FACTORY_ABI,
      functionName: 'upgradeVaultBatch',
      args: [selectedVaultsForBatch as `0x${string}`[], upgradeImplAddr as `0x${string}`],
      gas: GAS_CONFIG.VERY_COMPLEX,
    });
  };

  // ===== 批量操作 =====
  const toggleVaultSelection = (vaultAddr: string) => {
    setSelectedVaultsForBatch(prev =>
      prev.includes(vaultAddr) ? prev.filter(v => v !== vaultAddr) : [...prev, vaultAddr]
    );
  };

  const toggleSelectAll = () => {
    if (!allVaults) return;
    setSelectedVaultsForBatch(
      selectedVaultsForBatch.length === allVaults.length ? [] : [...allVaults]
    );
  };

  const handleBatchUpdatePrices = () => {
    if (selectedVaultsForBatch.length === 0 || !batchYtPrice) return;
    const ytPrices = selectedVaultsForBatch.map(() => parseUnits(batchYtPrice, TOKEN_DECIMALS.INTERNAL_PRICE));
    writeContract({
      address: CONTRACTS.FACTORY,
      abi: FACTORY_ABI,
      functionName: 'updateVaultPricesBatch',
      args: [selectedVaultsForBatch as `0x${string}`[], ytPrices],
      gas: GAS_CONFIG.VERY_COMPLEX,
    });
  };

  const handleBatchSetHardCap = () => {
    if (selectedVaultsForBatch.length === 0 || !batchHardCap) return;
    const hardCaps = selectedVaultsForBatch.map(() => parseUnits(batchHardCap, TOKEN_DECIMALS.YT));
    writeContract({
      address: CONTRACTS.FACTORY,
      abi: FACTORY_ABI,
      functionName: 'setHardCapBatch',
      args: [selectedVaultsForBatch as `0x${string}`[], hardCaps],
      gas: GAS_CONFIG.VERY_COMPLEX,
    });
  };

  // ProTable 列定义
  const columns: ProColumns<VaultInfo>[] = [
    {
      title: intl.formatMessage({ id: 'pages.factory.symbol' }),
      dataIndex: 'symbol',
      width: 120,
    },
    {
      title: intl.formatMessage({ id: 'pages.holders.address' }),
      dataIndex: 'address',
      width: 180,
      render: (_, record) => (
        <Link href={`${blockExplorer}/address/${record.address}`} target="_blank">
          {`${record.address.slice(0, 6)}...${record.address.slice(-4)}`}
        </Link>
      ),
    },
    {
      title: intl.formatMessage({ id: 'pages.factory.status' }),
      dataIndex: 'paused',
      width: 100,
      render: (_, record) => (
        <Tag color={record.paused ? 'red' : 'green'}>
          {intl.formatMessage({ id: record.paused ? 'pages.factory.paused' : 'pages.factory.active' })}
        </Tag>
      ),
    },
    {
      title: intl.formatMessage({ id: 'pages.factory.actions' }),
      width: 200,
      render: (_, record) => (
        <Space>
          <Button
            size="small"
            icon={record.paused ? <PlayCircleOutlined /> : <PauseCircleOutlined />}
            onClick={() => handleTogglePause(record.address, record.paused)}
            loading={isProcessing}
          >
            {intl.formatMessage({ id: record.paused ? 'pages.factory.unpause' : 'pages.factory.pause' })}
          </Button>
          <Button
            size="small"
            icon={<EditOutlined />}
            onClick={() => setSelectedVault(record.address)}
          >
            {intl.formatMessage({ id: 'pages.factory.manageVault' })}
          </Button>
        </Space>
      ),
    },
  ];

  if (!isConnected) {
    return (
      <PageContainer>
        <ProCard>
          <Space direction="vertical" size="large" style={{ width: '100%', textAlign: 'center', padding: '40px 0' }}>
            <Text type="secondary">{intl.formatMessage({ id: 'pages.common.connectFirst' })}</Text>
          </Space>
        </ProCard>
      </PageContainer>
    );
  }

  return (
    <PageContainer
      title={`${intl.formatMessage({ id: 'pages.factory.title' })} (${currentChainName})`}
      extra={[
        <Button
          key="create"
          type="primary"
          icon={<PlusOutlined />}
          onClick={() => setShowCreateForm(!showCreateForm)}
        >
          {intl.formatMessage({ id: 'pages.factory.createVault' })}
        </Button>,
      ]}
    >
      <Space direction="vertical" size="large" style={{ width: '100%' }}>

        {/* 合约信息卡 */}
        <ProCard>
          <Descriptions column={{ xs: 1, sm: 2 }} size="small">
            <Descriptions.Item label={<Tooltip title="负责创建和管理所有 YT 金库的工厂合约地址">工厂合约</Tooltip>}>
              <Space>
                <Typography.Text code copyable={{ text: CONTRACTS.FACTORY }} style={{ fontSize: 14 }}>
                  {CONTRACTS.FACTORY}
                </Typography.Text>
              </Space>
            </Descriptions.Item>

            <Descriptions.Item label={<Tooltip title="工厂合约的所有者，拥有创建金库、更新价格等最高权限">所有者</Tooltip>}>
              <Space>
                <Typography.Text code style={{ fontSize: 14 }}>
                  {(owner as string) || '-'}
                </Typography.Text>
                {owner && (
                  <Button size="small" icon={<CopyOutlined />} type="text" onClick={() => copyToClipboard(owner as string)} />
                )}
              </Space>
            </Descriptions.Item>

            <Descriptions.Item label={<Tooltip title="金库代理合约的实现地址，用于可升级架构">金库实现</Tooltip>}>
              <Typography.Text code style={{ fontSize: 14 }}>
                {(vaultImplementation as string) || '-'}
              </Typography.Text>
            </Descriptions.Item>

            <Descriptions.Item label={<Tooltip title="当前连接钱包在工厂合约中的角色">你的角色</Tooltip>}>
              {isOwner ? (
                <Badge status="success" text={<Tag color="green">Owner（所有者）</Tag>} />
              ) : (
                <Badge status="default" text={<Tag>普通用户</Tag>} />
              )}
            </Descriptions.Item>
          </Descriptions>
        </ProCard>

        {/* 统计卡片 */}
        <Row gutter={[16, 16]}>
          <Col xs={24} sm={12} md={8}>
            <StatisticCard
              statistic={{
                title: intl.formatMessage({ id: 'pages.factory.vaultCount' }),
                value: vaultCount ? vaultCount.toString() : '0',
              }}
            />
          </Col>
          <Col xs={24} sm={12} md={8}>
            <StatisticCard
              statistic={{
                title: intl.formatMessage({ id: 'pages.factory.owner' }),
                value: owner ? `${(owner as string).slice(0, 6)}...${(owner as string).slice(-4)}` : '--',
                description: isOwner ? <Tag color="green">当前账户是 Owner</Tag> : null,
              }}
            />
          </Col>
          <Col xs={24} sm={12} md={8}>
            <StatisticCard
              statistic={{
                title: `${intl.formatMessage({ id: 'pages.vault.hardCap' })} (Default)`,
                value: defaultHardCap ? Number(formatUnits(defaultHardCap as bigint, TOKEN_DECIMALS.YT)).toFixed(0) : '--',
              }}
            />
          </Col>
        </Row>

        {/* 创建金库表单 */}
        {showCreateForm && (
          <ProCard title={intl.formatMessage({ id: 'pages.factory.createVault' })}>
            <ProForm
              onFinish={handleCreateVault}
              submitter={{
                searchConfig: { submitText: intl.formatMessage({ id: 'pages.factory.create' }) },
                render: (_, dom) => <Space>{dom}</Space>,
              }}
            >
              <ProForm.Group>
                <ProFormText name="name" label={intl.formatMessage({ id: 'pages.factory.name' })} placeholder="YT-A Token" rules={[{ required: true }]} />
                <ProFormText name="symbol" label={intl.formatMessage({ id: 'pages.factory.symbol' })} placeholder="YT-A" rules={[{ required: true }]} />
                <ProFormText
                  name="manager"
                  label={intl.formatMessage({ id: 'pages.factory.manager' })}
                  placeholder="0x..."
                  rules={[{ required: true }, { pattern: /^0x[a-fA-F0-9]{40}$/, message: 'Invalid address' }]}
                />
              </ProForm.Group>
              <ProForm.Group>
                <ProFormDigit name="hardCap" label={intl.formatMessage({ id: 'pages.vault.hardCap' })} placeholder="100000" fieldProps={{ precision: 0 }} />
                <ProFormDigit name="redemptionTime" label={`${intl.formatMessage({ id: 'pages.factory.redemptionTime' })} (timestamp)`} placeholder="86400" fieldProps={{ precision: 0 }} />
                <ProFormDigit name="initialYtPrice" label={intl.formatMessage({ id: 'pages.factory.initialYtPrice' })} placeholder="1.0" fieldProps={{ precision: 6 }} />
              </ProForm.Group>
            </ProForm>
          </ProCard>
        )}

        {/* 管理选中的金库（表格行点击） */}
        {selectedVault && (
          <ProCard title={`${intl.formatMessage({ id: 'pages.factory.manageVault' })}: ${selectedVault.slice(0, 10)}...`}>
            <Space direction="vertical" size="middle" style={{ width: '100%' }}>
              <ProForm
                layout="inline"
                onFinish={(values) => handleUpdatePrice(selectedVault, values)}
                submitter={{ searchConfig: { submitText: intl.formatMessage({ id: 'pages.factory.updatePrice' }) } }}
              >
                <ProFormDigit name="ytPrice" label={intl.formatMessage({ id: 'pages.vault.ytPrice' })} placeholder="1.0" fieldProps={{ precision: 6 }} rules={[{ required: true }]} />
              </ProForm>
              <ProForm
                layout="inline"
                onFinish={(values) => handleUpdateHardCap(selectedVault, values)}
                submitter={{ searchConfig: { submitText: intl.formatMessage({ id: 'pages.factory.updateHardCap' }) } }}
              >
                <ProFormDigit name="hardCap" label={intl.formatMessage({ id: 'pages.vault.hardCap' })} placeholder="100000" fieldProps={{ precision: 0 }} rules={[{ required: true }]} />
              </ProForm>
              <Button onClick={() => setSelectedVault(null)}>关闭</Button>
            </Space>
          </ProCard>
        )}

        {/* 金库列表 */}
        <ProCard title={intl.formatMessage({ id: 'pages.factory.vaultList' })}>
          <ProTable<VaultInfo>
            columns={columns}
            dataSource={vaultTableData}
            rowKey="address"
            search={false}
            loading={isProcessing}
            options={{
              reload: () => { refetchVaults(); refetchPaused(); },
              density: true,
            }}
            pagination={{ pageSize: 10, showSizeChanger: true }}
          />
        </ProCard>

        {/* Owner 配置 + 批量操作 + 权限测试 — 用 Collapse 统一管理，有内置箭头和 pointer */}
        <Collapse
          accordion={false}
          items={[
            {
              key: 'ownerConfig',
              label: (
                <Space>
                  <SettingOutlined />
                  <Text strong>Owner 配置</Text>
                  {!isOwner && <Tag color="warning">需要 Owner 权限</Tag>}
                </Space>
              ),
              children: (
                <Space direction="vertical" size="large" style={{ width: '100%' }}>
                  {!isOwner && (
                    <Alert message="当前账户不是 Factory Owner，操作将被拒绝" type="warning" showIcon />
                  )}

                  {/* 单金库管理 */}
                  <ProCard title="单金库管理" bordered>
                    <Form layout="vertical">
                      <Form.Item label="选择金库">
                        <Select
                          value={selectedVaultForManage || undefined}
                          onChange={setSelectedVaultForManage}
                          placeholder="请选择金库"
                          style={{ width: '100%' }}
                          options={vaultTableData.map((v, i) => ({
                            value: v.address,
                            label: `${v.symbol || `Vault ${i + 1}`}: ${v.address}`,
                          }))}
                        />
                      </Form.Item>
                    </Form>

                    {selectedVaultForManage && (
                      <Row gutter={[16, 16]}>
                        <Col xs={24} md={12}>
                          <ProCard title="更新 YT 价格" bordered size="small">
                            <Text type="secondary" style={{ fontSize: 14 }}>USDC 价格由 Chainlink 自动提供，只需填 YT 价格</Text>
                            <div style={{ display: 'flex', gap: 8, marginTop: 8 }}>
                              <Input type="number" value={singleVaultYtPrice} onChange={(e) => setSingleVaultYtPrice(e.target.value)} placeholder="1.0" style={{ flex: 1 }} step="0.01" />
                              <Button type="primary" loading={isProcessing} onClick={handleUpdateSingleVaultYTPrice} disabled={!singleVaultYtPrice}>更新价格</Button>
                            </div>
                          </ProCard>
                        </Col>
                        <Col xs={24} md={12}>
                          <ProCard title="设置硬顶" bordered size="small">
                            <div style={{ display: 'flex', gap: 8 }}>
                              <Input type="number" value={singleVaultHardCap} onChange={(e) => setSingleVaultHardCap(e.target.value)} placeholder="100000" style={{ flex: 1 }} />
                              <Button loading={isProcessing} onClick={handleSetSingleVaultHardCap} disabled={!singleVaultHardCap}>设置</Button>
                            </div>
                          </ProCard>
                        </Col>
                        <Col xs={24} md={12}>
                          <ProCard title="设置赎回时间" bordered size="small">
                            <div style={{ display: 'flex', gap: 8 }}>
                              <DatePicker
                                showTime
                                style={{ flex: 1 }}
                                value={singleVaultRedemptionTime ? dayjs(singleVaultRedemptionTime) : null}
                                onChange={(date) => setSingleVaultRedemptionTime(date ? date.toISOString() : '')}
                              />
                              <Button loading={isProcessing} onClick={handleSetSingleVaultRedemptionTime} disabled={!singleVaultRedemptionTime}>设置</Button>
                            </div>
                          </ProCard>
                        </Col>
                        <Col xs={24} md={12}>
                          <ProCard title="设置管理员" bordered size="small">
                            <div style={{ display: 'flex', gap: 8 }}>
                              <Input value={singleVaultManager} onChange={(e) => setSingleVaultManager(e.target.value)} placeholder="0x..." style={{ flex: 1 }} />
                              <Button loading={isProcessing} onClick={handleSetSingleVaultManager} disabled={!singleVaultManager}>设置</Button>
                            </div>
                          </ProCard>
                        </Col>
                      </Row>
                    )}
                  </ProCard>

                  {/* 设置全局默认硬顶 */}
                  <ProCard title="设置默认硬顶 (全局)" bordered>
                    <Text type="secondary" style={{ display: 'block', marginBottom: 8 }}>
                      当前默认硬顶：{defaultHardCap ? Number(formatUnits(defaultHardCap as bigint, TOKEN_DECIMALS.YT)).toFixed(0) : '--'}
                    </Text>
                    <div style={{ display: 'flex', gap: 8, maxWidth: 480 }}>
                      <Input type="number" value={newDefaultHardCap} onChange={(e) => setNewDefaultHardCap(e.target.value)} placeholder="1000000" style={{ flex: 1 }} />
                      <Button type="primary" loading={isProcessing} onClick={handleSetDefaultHardCap} disabled={!newDefaultHardCap}>确认</Button>
                    </div>
                  </ProCard>
                </Space>
              ),
            },
            {
              key: 'batchOps',
              label: (
                <Space>
                  <ThunderboltOutlined />
                  <Text strong>批量操作</Text>
                </Space>
              ),
              children: (
                <Space direction="vertical" size="large" style={{ width: '100%' }}>
                  <ProCard title="选择金库" bordered>
                    <Space style={{ marginBottom: 12 }}>
                      <Button size="small" onClick={toggleSelectAll}>
                        {allVaults && selectedVaultsForBatch.length === allVaults.length ? '取消全选' : '全选'}
                      </Button>
                      <Text type="secondary">已选 {selectedVaultsForBatch.length} / {vaultTableData.length} 个</Text>
                    </Space>
                    <Space wrap>
                      {vaultTableData.map((vault) => (
                        <Checkbox key={vault.address} checked={selectedVaultsForBatch.includes(vault.address)} onChange={() => toggleVaultSelection(vault.address)}>
                          <Tag color={vault.paused ? 'red' : 'green'}>{vault.symbol || vault.address.slice(0, 8)}</Tag>
                        </Checkbox>
                      ))}
                    </Space>
                  </ProCard>

                  {selectedVaultsForBatch.length > 0 && (
                    <Row gutter={[16, 16]}>
                      <Col xs={24} md={12}>
                        <ProCard title="批量更新 YT 价格" bordered>
                          <div style={{ display: 'flex', gap: 8 }}>
                            <Input type="number" value={batchYtPrice} onChange={(e) => setBatchYtPrice(e.target.value)} placeholder="1.0" style={{ flex: 1 }} step="0.01" />
                            <Button type="primary" loading={isProcessing} onClick={handleBatchUpdatePrices} disabled={!batchYtPrice}>
                              批量更新 ({selectedVaultsForBatch.length} 个)
                            </Button>
                          </div>
                        </ProCard>
                      </Col>
                      <Col xs={24} md={12}>
                        <ProCard title="批量设置硬顶" bordered>
                          <div style={{ display: 'flex', gap: 8 }}>
                            <Input type="number" value={batchHardCap} onChange={(e) => setBatchHardCap(e.target.value)} placeholder="100000" style={{ flex: 1 }} />
                            <Button loading={isProcessing} onClick={handleBatchSetHardCap} disabled={!batchHardCap}>
                              批量设置 ({selectedVaultsForBatch.length} 个)
                            </Button>
                          </div>
                        </ProCard>
                      </Col>
                      <Col xs={24} md={12}>
                        <ProCard title="批量设置赎回时间" bordered>
                          <div style={{ display: 'flex', gap: 8 }}>
                            <DatePicker
                              showTime
                              style={{ flex: 1 }}
                              value={batchRedemptionTime ? dayjs(batchRedemptionTime) : null}
                              onChange={(date) => setBatchRedemptionTime(date ? date.toISOString() : '')}
                            />
                            <Button loading={isProcessing} onClick={handleBatchSetRedemptionTime} disabled={!batchRedemptionTime}>
                              批量设置 ({selectedVaultsForBatch.length} 个)
                            </Button>
                          </div>
                        </ProCard>
                      </Col>
                      <Col xs={24} md={12}>
                        <ProCard title="批量暂停 / 恢复" bordered>
                          <Space>
                            <Button
                              icon={<PauseCircleOutlined />}
                              loading={isProcessing}
                              onClick={handleBatchPauseVaults}
                            >
                              批量暂停 ({selectedVaultsForBatch.length} 个)
                            </Button>
                            <Button
                              icon={<PlayCircleOutlined />}
                              loading={isProcessing}
                              onClick={handleBatchUnpauseVaults}
                            >
                              批量恢复 ({selectedVaultsForBatch.length} 个)
                            </Button>
                          </Space>
                        </ProCard>
                      </Col>
                    </Row>
                  )}

                  {/* 批量创建金库 */}
                  <Collapse
                    items={[{
                      key: 'batchCreate',
                      label: <Space><PlusOutlined /><Text strong>批量创建金库</Text></Space>,
                      children: (
                        <Space direction="vertical" size="middle" style={{ width: '100%' }}>
                          {batchCreateVaults.map((vault, index) => (
                            <ProCard
                              key={index}
                              title={<Space><Text strong>Vault {index + 1}</Text>{batchCreateVaults.length > 1 && <Button size="small" danger onClick={() => removeBatchCreateRow(index)}>删除</Button>}</Space>}
                              bordered
                              size="small"
                            >
                              <Row gutter={[8, 8]}>
                                <Col xs={12} md={6}>
                                  <Input placeholder="名称 YT-X" value={vault.name} onChange={(e) => updateBatchCreateRow(index, 'name', e.target.value)} />
                                </Col>
                                <Col xs={12} md={6}>
                                  <Input placeholder="符号 YTX" value={vault.symbol} onChange={(e) => updateBatchCreateRow(index, 'symbol', e.target.value)} />
                                </Col>
                                <Col xs={24} md={12}>
                                  <Input placeholder="Manager 地址 0x..." value={vault.manager} onChange={(e) => updateBatchCreateRow(index, 'manager', e.target.value)} />
                                </Col>
                                <Col xs={12} md={6}>
                                  <Input type="number" placeholder="硬顶 100000" value={vault.hardCap} onChange={(e) => updateBatchCreateRow(index, 'hardCap', e.target.value)} />
                                </Col>
                                <Col xs={12} md={6}>
                                  <Input type="number" placeholder="YT 初始价格 1" value={vault.ytPrice} onChange={(e) => updateBatchCreateRow(index, 'ytPrice', e.target.value)} />
                                </Col>
                                <Col xs={24} md={12}>
                                  <DatePicker
                                    showTime
                                    style={{ width: '100%' }}
                                    value={vault.redemptionTime ? dayjs(vault.redemptionTime) : null}
                                    onChange={(date) => updateBatchCreateRow(index, 'redemptionTime', date ? date.toISOString() : '')}
                                  />
                                </Col>
                              </Row>
                            </ProCard>
                          ))}
                          <Space>
                            <Button icon={<PlusOutlined />} onClick={addBatchCreateRow}>添加一行</Button>
                            <Button
                              type="primary"
                              loading={isProcessing}
                              onClick={handleBatchCreateVaults}
                              disabled={batchCreateVaults.filter(v => v.name && v.symbol && v.manager && v.hardCap && v.redemptionTime).length === 0}
                            >
                              批量创建 ({batchCreateVaults.filter(v => v.name && v.symbol && v.manager && v.hardCap && v.redemptionTime).length} 个)
                            </Button>
                          </Space>
                        </Space>
                      ),
                    }]}
                  />
                </Space>
              ),
            },
            {
              key: 'advanced',
              label: (
                <Space>
                  <SettingOutlined />
                  <Text strong>高级功能</Text>
                  <Tag color="red">危险操作</Tag>
                </Space>
              ),
              children: (
                <Space direction="vertical" size="large" style={{ width: '100%' }}>
                  <Alert message="以下操作涉及合约升级和实现变更，请谨慎操作。" type="warning" showIcon />

                  {/* 验证金库地址 */}
                  <ProCard title="验证金库地址" bordered size="small">
                    <Text type="secondary" style={{ display: 'block', marginBottom: 8, fontSize: 14 }}>
                      使用 isVault() 验证地址是否为工厂创建的有效金库
                    </Text>
                    <Space>
                      <Input
                        value={checkVaultAddr}
                        onChange={(e) => setCheckVaultAddr(e.target.value)}
                        placeholder="0x..."
                        style={{ width: 420 }}
                      />
                      {checkVaultAddr && checkVaultAddr.length === 42 && (
                        <Tag color={isValidVault ? 'green' : 'red'}>
                          {isValidVault ? '✓ 有效金库' : '✗ 不是金库'}
                        </Tag>
                      )}
                    </Space>
                  </ProCard>

                  <Row gutter={[16, 16]}>
                    {/* 设置金库实现地址 */}
                    <Col xs={24} md={12}>
                      <ProCard title="设置金库实现地址" bordered size="small">
                        <Text type="secondary" style={{ display: 'block', marginBottom: 8, fontSize: 14 }}>
                          当前实现: <Text code style={{ fontSize: 12 }}>{(vaultImplementation as string) || '-'}</Text>
                        </Text>
                        <div style={{ display: 'flex', gap: 8 }}>
                          <Input value={newImplementation} onChange={(e) => setNewImplementation(e.target.value)} placeholder="新实现地址 0x..." style={{ flex: 1 }} />
                          <Button danger loading={isProcessing} onClick={handleSetVaultImplementation} disabled={!newImplementation}>设置</Button>
                        </div>
                      </ProCard>
                    </Col>

                    {/* 升级单个金库 */}
                    <Col xs={24} md={12}>
                      <ProCard title="升级单个金库" bordered size="small">
                        <Space direction="vertical" style={{ width: '100%' }}>
                          <Select
                            value={upgradeVaultAddr || undefined}
                            onChange={setUpgradeVaultAddr}
                            placeholder="选择金库"
                            style={{ width: '100%' }}
                            options={vaultTableData.map((v) => ({ value: v.address, label: `${v.symbol}: ${v.address.slice(0, 10)}...` }))}
                          />
                          <div style={{ display: 'flex', gap: 8 }}>
                            <Input value={upgradeImplAddr} onChange={(e) => setUpgradeImplAddr(e.target.value)} placeholder="新实现地址 0x..." style={{ flex: 1 }} />
                            <Button danger loading={isProcessing} onClick={handleUpgradeVault} disabled={!upgradeVaultAddr || !upgradeImplAddr}>升级</Button>
                          </div>
                        </Space>
                      </ProCard>
                    </Col>

                    {/* 批量升级金库 */}
                    <Col xs={24}>
                      <ProCard title="批量升级金库" bordered size="small">
                        <Text type="secondary" style={{ display: 'block', marginBottom: 8, fontSize: 14 }}>
                          将在"批量操作"中已选的 {selectedVaultsForBatch.length} 个金库全部升级
                        </Text>
                        <div style={{ display: 'flex', gap: 8 }}>
                          <Input value={upgradeImplAddr} onChange={(e) => setUpgradeImplAddr(e.target.value)} placeholder="新实现地址 0x..." style={{ flex: 1 }} />
                          <Button danger loading={isProcessing} onClick={handleBatchUpgradeVault} disabled={selectedVaultsForBatch.length === 0 || !upgradeImplAddr}>
                            批量升级 ({selectedVaultsForBatch.length} 个)
                          </Button>
                        </div>
                      </ProCard>
                    </Col>
                  </Row>
                </Space>
              ),
            },
            {
              key: 'permissionTest',
              label: (
                <Space>
                  <SafetyOutlined />
                  <Text strong>功能权限测试</Text>
                  <Tag color="blue">仅用于调试</Tag>
                </Space>
              ),
              children: (
                <Space direction="vertical" size="large" style={{ width: '100%' }}>
                  <Alert message="以下测试会向合约发送实际交易。如果权限控制正常，非 Owner 操作将被合约拒绝（Revert）。" type="info" showIcon />
                  {isOwner && (
                    <Alert message="当前账户是 Owner，测试将成功执行而非被拒绝。" type="warning" showIcon />
                  )}
                  <Row gutter={[16, 16]}>
                    <Col xs={24} md={12}>
                      <ProCard bordered size="small">
                        <Space direction="vertical" style={{ width: '100%' }}>
                          <Space>
                            <Tag color="red">预期: Unauthorized</Tag>
                            <Text strong>更新价格（非 Owner）</Text>
                          </Space>
                          <Text type="secondary" style={{ fontSize: 14 }}>
                            调用 updateVaultPrices，验证非 Owner 无法更新金库价格
                          </Text>
                          <Button
                            size="small"
                            onClick={() => runPermissionTest('update_price_not_owner')}
                            loading={runningTest === 'update_price_not_owner'}
                            disabled={isProcessing || !allVaults || allVaults.length === 0}
                          >
                            执行测试
                          </Button>
                        </Space>
                      </ProCard>
                    </Col>
                    <Col xs={24} md={12}>
                      <ProCard bordered size="small">
                        <Space direction="vertical" style={{ width: '100%' }}>
                          <Space>
                            <Tag color="red">预期: Unauthorized</Tag>
                            <Text strong>设置管理员（非 Owner）</Text>
                          </Space>
                          <Text type="secondary" style={{ fontSize: 14 }}>
                            调用 setVaultManager，验证非 Owner 无法设置金库管理员
                          </Text>
                          <Button
                            size="small"
                            onClick={() => runPermissionTest('set_manager_not_owner')}
                            loading={runningTest === 'set_manager_not_owner'}
                            disabled={isProcessing || !allVaults || allVaults.length === 0}
                          >
                            执行测试
                          </Button>
                        </Space>
                      </ProCard>
                    </Col>
                  </Row>
                </Space>
              ),
            },
          ]}
        />

      </Space>
    </PageContainer>
  );
}
