'use client';

import { useState, useEffect, useCallback } from 'react';
import styles from './co-managed-wallet.module.scss';
import CreateWalletModal from './CreateWalletModal';
import {
  coManagedWalletService,
  CoManagedWallet as ApiWallet,
} from '@/services/coManagedWalletService';

interface CoManagedWallet {
  id: string;
  name: string;
  publicKey: string;
  threshold: { t: number; n: number };
  participantCount: number;
  createdAt: string;
  status: 'active' | 'pending';
}

/**
 * 将 API 钱包转换为本地类型
 */
function mapApiWalletToLocal(apiWallet: ApiWallet): CoManagedWallet {
  return {
    id: apiWallet.id,
    name: apiWallet.name,
    publicKey: apiWallet.publicKey,
    threshold: apiWallet.threshold,
    participantCount: apiWallet.participantCount,
    createdAt: apiWallet.createdAt,
    status: 'active',
  };
}

/**
 * 共管钱包管理区域组件
 */
export default function CoManagedWalletSection() {
  const [isModalOpen, setIsModalOpen] = useState(false);
  const [wallets, setWallets] = useState<CoManagedWallet[]>([]);
  const [isLoading, setIsLoading] = useState(true);
  const [error, setError] = useState<string | null>(null);

  // 加载钱包列表
  const loadWallets = useCallback(async () => {
    setIsLoading(true);
    setError(null);

    try {
      const result = await coManagedWalletService.listWallets({ page: 1, pageSize: 50 });
      const mappedWallets = result.items.map(mapApiWalletToLocal);
      setWallets(mappedWallets);
    } catch (err) {
      console.error('加载钱包列表失败:', err);
      setError('加载钱包列表失败');
    } finally {
      setIsLoading(false);
    }
  }, []);

  // 初始加载
  useEffect(() => {
    loadWallets();
  }, [loadWallets]);

  // 创建成功后刷新列表
  const handleCreateSuccess = () => {
    loadWallets();
  };

  const formatDate = (dateStr: string) => {
    try {
      return new Date(dateStr).toLocaleDateString('zh-CN');
    } catch {
      return dateStr;
    }
  };

  const truncateKey = (key: string) => {
    if (key.length <= 20) return key;
    return `${key.slice(0, 10)}...${key.slice(-8)}`;
  };

  return (
    <section className={styles.coManagedWalletSection}>
      <div className={styles.coManagedWalletSection__header}>
        <div>
          <h3 className={styles.coManagedWalletSection__title}>共管钱包管理</h3>
          <p className={styles.coManagedWalletSection__desc}>
            创建和管理分布式多方共管钱包，支持多人协同签名
          </p>
        </div>
        <button
          type="button"
          className={styles.coManagedWalletSection__createBtn}
          onClick={() => setIsModalOpen(true)}
        >
          创建共管钱包
        </button>
      </div>

      {isLoading ? (
        <div className={styles.coManagedWalletSection__loading}>加载中...</div>
      ) : error ? (
        <div className={styles.coManagedWalletSection__error}>
          <p>{error}</p>
          <button
            type="button"
            className={styles.coManagedWalletSection__retryBtn}
            onClick={loadWallets}
          >
            重试
          </button>
        </div>
      ) : wallets.length === 0 ? (
        <div className={styles.coManagedWalletSection__empty}>
          <div className={styles.coManagedWalletSection__emptyIcon}>🔐</div>
          <p className={styles.coManagedWalletSection__emptyText}>暂无共管钱包</p>
          <p className={styles.coManagedWalletSection__emptyHint}>
            创建共管钱包后，多个参与方可以共同管理资产
          </p>
          <button
            type="button"
            className={styles.coManagedWalletSection__emptyBtn}
            onClick={() => setIsModalOpen(true)}
          >
            创建第一个共管钱包
          </button>
        </div>
      ) : (
        <div className={styles.coManagedWalletSection__grid}>
          {wallets.map((wallet) => (
            <div key={wallet.id} className={styles.walletCard}>
              <div className={styles.walletCard__header}>
                <h4 className={styles.walletCard__name}>{wallet.name}</h4>
                <span className={styles.walletCard__threshold}>
                  {wallet.threshold.t}-of-{wallet.threshold.n}
                </span>
              </div>
              <div className={styles.walletCard__body}>
                <div className={styles.walletCard__row}>
                  <span className={styles.walletCard__label}>公钥</span>
                  <code className={styles.walletCard__value}>
                    {truncateKey(wallet.publicKey)}
                  </code>
                </div>
                <div className={styles.walletCard__row}>
                  <span className={styles.walletCard__label}>参与方</span>
                  <span className={styles.walletCard__value}>
                    {wallet.participantCount} 人
                  </span>
                </div>
                <div className={styles.walletCard__row}>
                  <span className={styles.walletCard__label}>创建时间</span>
                  <span className={styles.walletCard__value}>
                    {formatDate(wallet.createdAt)}
                  </span>
                </div>
              </div>
              <div className={styles.walletCard__footer}>
                <button type="button" className={styles.walletCard__actionBtn}>
                  查看详情
                </button>
              </div>
            </div>
          ))}
        </div>
      )}

      <p className={styles.coManagedWalletSection__help}>
        帮助：共管钱包使用 MPC (多方计算) 技术，无需暴露完整私钥即可进行安全签名。
        每个参与方持有密钥份额，需要达到阈值数量的参与方才能完成签名。
      </p>

      <CreateWalletModal
        isOpen={isModalOpen}
        onClose={() => setIsModalOpen(false)}
        onSuccess={handleCreateSuccess}
      />
    </section>
  );
}
