'use client';

/**
 * [2026-02-19] 树转让管理列表页（纯新增）
 *
 * 管理员端的树转让管理页面，提供：
 * - 统计汇总（总数/待处理/已完成/已取消/失败/总成交额）
 * - 关键字搜索 + 状态筛选 + 分页
 * - 转让订单表格（点击订单号跳详情）
 * - 13 种 Saga 状态 badge 颜色映射
 *
 * === 回滚方式 ===
 * 删除 transfers/ 目录即可
 */

import { useState } from 'react';
import Link from 'next/link';
import { Button } from '@/components/common';
import { PageContainer } from '@/components/layout';
import { cn } from '@/utils/helpers';
import { formatDateTime } from '@/utils/formatters';
import { useTransferStats, useTransferList } from '@/hooks';
import type { TransferOrder, TransferOrderStatus } from '@/services/transferService';
import styles from './transfers.module.scss';

// 状态显示映射（13 种）
const STATUS_MAP: Record<TransferOrderStatus, { label: string; style: string }> = {
  PENDING: { label: '待确认', style: 'pending' },
  SELLER_CONFIRMED: { label: '卖方已确认', style: 'sellerConfirmed' },
  PAYMENT_FROZEN: { label: '资金已冻结', style: 'paymentFrozen' },
  TREES_LOCKED: { label: '树已锁定', style: 'treesLocked' },
  OWNERSHIP_TRANSFERRED: { label: '所有权变更', style: 'ownershipTransferred' },
  CONTRIBUTION_ADJUSTED: { label: '算力调整', style: 'contributionAdjusted' },
  STATS_UPDATED: { label: '统计更新', style: 'statsUpdated' },
  PAYMENT_SETTLED: { label: '资金结算', style: 'paymentSettled' },
  COMPLETED: { label: '已完成', style: 'completed' },
  CANCELLED: { label: '已取消', style: 'cancelled' },
  FAILED: { label: '失败', style: 'failed' },
  ROLLING_BACK: { label: '补偿中', style: 'rollingBack' },
  ROLLED_BACK: { label: '已回滚', style: 'rolledBack' },
};

// 状态筛选选项
const STATUS_OPTIONS: { value: TransferOrderStatus | ''; label: string }[] = [
  { value: '', label: '全部状态' },
  { value: 'PENDING', label: '待确认' },
  { value: 'SELLER_CONFIRMED', label: '卖方已确认' },
  { value: 'PAYMENT_FROZEN', label: '资金已冻结' },
  { value: 'COMPLETED', label: '已完成' },
  { value: 'CANCELLED', label: '已取消' },
  { value: 'FAILED', label: '失败' },
  { value: 'ROLLING_BACK', label: '补偿中' },
  { value: 'ROLLED_BACK', label: '已回滚' },
];

/**
 * 转让管理列表页
 */
export default function TransfersPage() {
  const [keyword, setKeyword] = useState('');
  const [statusFilter, setStatusFilter] = useState<TransferOrderStatus | ''>('');
  const [page, setPage] = useState(1);
  const pageSize = 20;

  const { data: stats, isLoading: statsLoading } = useTransferStats();
  const listQuery = useTransferList({
    page,
    pageSize,
    keyword: keyword || undefined,
    status: statusFilter || undefined,
  });

  const formatNumber = (n: number) => n.toLocaleString('en-US');

  const totalPages = listQuery.data ? Math.ceil(listQuery.data.total / pageSize) : 0;

  return (
    <PageContainer title="转让管理">
      <div className={styles.transfers}>
        {/* 页面标题 */}
        <div className={styles.transfers__header}>
          <h1 className={styles.transfers__title}>树转让管理</h1>
        </div>

        {/* 统计卡片 */}
        <div className={styles.transfers__statsGrid}>
          <div className={styles.transfers__statCard}>
            <div className={styles.transfers__statValue}>
              {statsLoading ? '-' : formatNumber(stats?.totalOrders ?? 0)}
            </div>
            <div className={styles.transfers__statLabel}>总订单数</div>
          </div>
          <div className={styles.transfers__statCard}>
            <div className={styles.transfers__statValue}>
              {statsLoading ? '-' : formatNumber(stats?.pendingOrders ?? 0)}
            </div>
            <div className={styles.transfers__statLabel}>待处理</div>
          </div>
          <div className={styles.transfers__statCard}>
            <div className={styles.transfers__statValue}>
              {statsLoading ? '-' : formatNumber(stats?.completedOrders ?? 0)}
            </div>
            <div className={styles.transfers__statLabel}>已完成</div>
          </div>
          <div className={styles.transfers__statCard}>
            <div className={styles.transfers__statValue}>
              {statsLoading ? '-' : formatNumber(stats?.cancelledOrders ?? 0)}
            </div>
            <div className={styles.transfers__statLabel}>已取消</div>
          </div>
          <div className={styles.transfers__statCard}>
            <div className={styles.transfers__statValue}>
              {statsLoading ? '-' : formatNumber(stats?.totalVolume ?? 0)}
            </div>
            <div className={styles.transfers__statLabel}>总成交额 (USDT)</div>
          </div>
        </div>

        {/* 数据区 */}
        <div className={styles.transfers__card}>
          {/* 工具栏：搜索 + 筛选 + 刷新 */}
          <div className={styles.transfers__toolbar}>
            <div className={styles.transfers__toolbarLeft}>
              <div className={styles.transfers__search}>
                <input
                  type="text"
                  placeholder="搜索订单号或用户账号..."
                  value={keyword}
                  onChange={(e) => {
                    setKeyword(e.target.value);
                    setPage(1);
                  }}
                />
              </div>
              <div className={styles.transfers__filter}>
                <select
                  value={statusFilter}
                  onChange={(e) => {
                    setStatusFilter(e.target.value as TransferOrderStatus | '');
                    setPage(1);
                  }}
                >
                  {STATUS_OPTIONS.map((opt) => (
                    <option key={opt.value} value={opt.value}>
                      {opt.label}
                    </option>
                  ))}
                </select>
              </div>
            </div>
            <Button
              variant="outline"
              size="sm"
              onClick={() => listQuery.refetch()}
            >
              刷新
            </Button>
          </div>

          {/* 表格 */}
          <TransfersTable
            data={listQuery.data?.items ?? []}
            loading={listQuery.isLoading}
            error={listQuery.error}
            onRetry={() => listQuery.refetch()}
          />

          {/* 分页 */}
          {totalPages > 1 && (
            <div className={styles.transfers__pagination}>
              <button
                className={styles.transfers__pageBtn}
                disabled={page <= 1}
                onClick={() => setPage(page - 1)}
              >
                上一页
              </button>
              <span className={styles.transfers__pageInfo}>
                {page} / {totalPages}
              </span>
              <button
                className={styles.transfers__pageBtn}
                disabled={page >= totalPages}
                onClick={() => setPage(page + 1)}
              >
                下一页
              </button>
            </div>
          )}
        </div>
      </div>
    </PageContainer>
  );
}

// ============================================
// 子组件：转让订单表格
// ============================================

function TransfersTable({
  data,
  loading,
  error,
  onRetry,
}: {
  data: TransferOrder[];
  loading: boolean;
  error: Error | null;
  onRetry: () => void;
}) {
  if (loading) return <div className={styles.transfers__loading}>加载中...</div>;
  if (error) {
    return (
      <div className={styles.transfers__error}>
        <span>{error.message || '加载失败'}</span>
        <Button variant="outline" size="sm" onClick={onRetry}>重试</Button>
      </div>
    );
  }
  if (data.length === 0) return <div className={styles.transfers__empty}>暂无转让订单</div>;

  return (
    <table className={styles.transfers__table}>
      <thead>
        <tr>
          <th>转让单号</th>
          <th>卖方</th>
          <th>买方</th>
          <th>棵数</th>
          <th>单价 (USDT)</th>
          <th>总价 (USDT)</th>
          <th>状态</th>
          <th>创建时间</th>
        </tr>
      </thead>
      <tbody>
        {data.map((order) => {
          const status = STATUS_MAP[order.status] ?? { label: order.status, style: '' };
          return (
            <tr key={order.id}>
              <td>
                <Link
                  href={`/transfers/${order.transferOrderNo}`}
                  className={styles.transfers__orderLink}
                >
                  {order.transferOrderNo}
                </Link>
              </td>
              <td>{order.sellerAccountSequence}</td>
              <td>{order.buyerAccountSequence}</td>
              <td>{order.treeCount}</td>
              <td>{Number(order.pricePerTree).toLocaleString()}</td>
              <td>{Number(order.totalPrice).toLocaleString()}</td>
              <td>
                <span className={cn(styles.transfers__status, styles[`transfers__status--${status.style}`])}>
                  {status.label}
                </span>
              </td>
              <td>{formatDateTime(order.createdAt)}</td>
            </tr>
          );
        })}
      </tbody>
    </table>
  );
}
