'use client';

/**
 * [2026-02-19] 树转让详情页（纯新增）
 *
 * 管理员查看单笔转让订单详情：
 * - 基本信息卡片（卖方/买方/金额/手续费）
 * - Saga 进度时间线（8 步可视化）
 * - 状态变更日志表格
 * - 强制取消按钮（非终态订单）
 *
 * === 回滚方式 ===
 * 删除 transfers/ 目录即可
 */

import { useState } from 'react';
import { useParams, useRouter } from 'next/navigation';
import { Button } from '@/components/common';
import { PageContainer } from '@/components/layout';
import { cn } from '@/utils/helpers';
import { formatDateTime } from '@/utils/formatters';
import { useTransferDetail, useForceCancel } from '@/hooks';
import type { TransferOrderStatus } from '@/services/transferService';
import styles from '../transfers.module.scss';

// Saga 步骤顺序
const SAGA_STEPS: { status: TransferOrderStatus; label: string }[] = [
  { status: 'PENDING', label: '待卖方确认' },
  { status: 'SELLER_CONFIRMED', label: '卖方已确认' },
  { status: 'PAYMENT_FROZEN', label: '买方资金冻结' },
  { status: 'TREES_LOCKED', label: '卖方树锁定' },
  { status: 'OWNERSHIP_TRANSFERRED', label: '所有权变更' },
  { status: 'CONTRIBUTION_ADJUSTED', label: '算力调整' },
  { status: 'STATS_UPDATED', label: '团队统计更新' },
  { status: 'PAYMENT_SETTLED', label: '资金结算' },
  { status: 'COMPLETED', label: '转让完成' },
];

// 状态标签映射
const STATUS_LABEL: Record<string, string> = {
  PENDING: '待确认',
  SELLER_CONFIRMED: '卖方已确认',
  PAYMENT_FROZEN: '资金已冻结',
  TREES_LOCKED: '树已锁定',
  OWNERSHIP_TRANSFERRED: '所有权变更',
  CONTRIBUTION_ADJUSTED: '算力调整',
  STATS_UPDATED: '统计更新',
  PAYMENT_SETTLED: '资金结算',
  COMPLETED: '已完成',
  CANCELLED: '已取消',
  FAILED: '失败',
  ROLLING_BACK: '补偿中',
  ROLLED_BACK: '已回滚',
};

// 终态判断
const TERMINAL_STATUSES = ['COMPLETED', 'CANCELLED', 'ROLLED_BACK'];

/**
 * 转让详情页
 */
export default function TransferDetailPage() {
  const params = useParams();
  const router = useRouter();
  const transferOrderNo = params.transferOrderNo as string;

  const { data: order, isLoading, error, refetch } = useTransferDetail(transferOrderNo);
  const forceCancel = useForceCancel();
  const [cancelReason, setCancelReason] = useState('');
  const [showCancelConfirm, setShowCancelConfirm] = useState(false);

  const handleForceCancel = () => {
    if (!cancelReason.trim()) return;
    forceCancel.mutate(
      { transferOrderNo, reason: cancelReason },
      {
        onSuccess: () => {
          setShowCancelConfirm(false);
          setCancelReason('');
          refetch();
        },
      },
    );
  };

  if (isLoading) {
    return (
      <PageContainer title="转让详情">
        <div className={styles.transfers__loading}>加载中...</div>
      </PageContainer>
    );
  }

  if (error || !order) {
    return (
      <PageContainer title="转让详情">
        <div className={styles.transfers__error}>
          <span>{error?.message || '订单不存在'}</span>
          <Button variant="outline" size="sm" onClick={() => refetch()}>重试</Button>
        </div>
      </PageContainer>
    );
  }

  const isTerminal = TERMINAL_STATUSES.includes(order.status);
  const currentStepIndex = SAGA_STEPS.findIndex((s) => s.status === order.status);
  const isFailed = order.status === 'FAILED' || order.status === 'ROLLING_BACK' || order.status === 'ROLLED_BACK';

  return (
    <PageContainer title={`转让详情 - ${transferOrderNo}`}>
      <div className={styles.transfers}>
        {/* 返回按钮 */}
        <button className={styles.transfers__backBtn} onClick={() => router.push('/transfers')}>
          &larr; 返回列表
        </button>

        {/* 页面标题 */}
        <div className={styles.transfers__header}>
          <h1 className={styles.transfers__title}>
            转让单：{order.transferOrderNo}
            <span
              className={cn(
                styles.transfers__status,
                styles[`transfers__status--${statusToStyle(order.status)}`],
              )}
              style={{ marginLeft: 12, fontSize: 14, verticalAlign: 'middle' }}
            >
              {STATUS_LABEL[order.status] || order.status}
            </span>
          </h1>
        </div>

        {/* 基本信息卡片 */}
        <div className={styles.transfers__card}>
          <div className={styles.transfers__detailGrid}>
            <div className={styles.transfers__detailItem}>
              <span className={styles.transfers__detailLabel}>卖方账号</span>
              <span className={styles.transfers__detailValue}>{order.sellerAccountSequence}</span>
            </div>
            <div className={styles.transfers__detailItem}>
              <span className={styles.transfers__detailLabel}>买方账号</span>
              <span className={styles.transfers__detailValue}>{order.buyerAccountSequence}</span>
            </div>
            <div className={styles.transfers__detailItem}>
              <span className={styles.transfers__detailLabel}>转让棵数</span>
              <span className={styles.transfers__detailValue}>{order.treeCount} 棵</span>
            </div>
            <div className={styles.transfers__detailItem}>
              <span className={styles.transfers__detailLabel}>单价</span>
              <span className={styles.transfers__detailValue}>{Number(order.pricePerTree).toLocaleString()} USDT</span>
            </div>
            <div className={styles.transfers__detailItem}>
              <span className={styles.transfers__detailLabel}>总价</span>
              <span className={styles.transfers__detailValue}>{Number(order.totalPrice).toLocaleString()} USDT</span>
            </div>
            <div className={styles.transfers__detailItem}>
              <span className={styles.transfers__detailLabel}>手续费率</span>
              <span className={styles.transfers__detailValue}>{(Number(order.platformFeeRate) * 100).toFixed(1)}%</span>
            </div>
            <div className={styles.transfers__detailItem}>
              <span className={styles.transfers__detailLabel}>手续费</span>
              <span className={styles.transfers__detailValue}>{Number(order.platformFeeAmount).toLocaleString()} USDT</span>
            </div>
            <div className={styles.transfers__detailItem}>
              <span className={styles.transfers__detailLabel}>卖方到账</span>
              <span className={styles.transfers__detailValue}>{Number(order.sellerReceiveAmount).toLocaleString()} USDT</span>
            </div>
            <div className={styles.transfers__detailItem}>
              <span className={styles.transfers__detailLabel}>创建时间</span>
              <span className={styles.transfers__detailValue}>{formatDateTime(order.createdAt)}</span>
            </div>
            {order.completedAt && (
              <div className={styles.transfers__detailItem}>
                <span className={styles.transfers__detailLabel}>完成时间</span>
                <span className={styles.transfers__detailValue}>{formatDateTime(order.completedAt)}</span>
              </div>
            )}
            {order.cancelledAt && (
              <div className={styles.transfers__detailItem}>
                <span className={styles.transfers__detailLabel}>取消时间</span>
                <span className={styles.transfers__detailValue}>{formatDateTime(order.cancelledAt)}</span>
              </div>
            )}
            {order.cancelReason && (
              <div className={styles.transfers__detailItem}>
                <span className={styles.transfers__detailLabel}>取消原因</span>
                <span className={styles.transfers__detailValue}>{order.cancelReason}</span>
              </div>
            )}
          </div>
        </div>

        {/* Saga 进度时间线 */}
        <div className={styles.transfers__section}>
          <h2 className={styles.transfers__sectionTitle}>Saga 进度</h2>
          <div className={styles.transfers__card}>
            <div className={styles.transfers__timeline}>
              {SAGA_STEPS.map((step, idx) => {
                let dotStyle = '';
                if (isFailed) {
                  dotStyle = idx <= currentStepIndex ? 'completed' : '';
                  if (idx === currentStepIndex) dotStyle = 'failed';
                } else if (idx < currentStepIndex || (isTerminal && idx <= currentStepIndex)) {
                  dotStyle = 'completed';
                } else if (idx === currentStepIndex) {
                  dotStyle = 'current';
                }

                // 从状态日志中查找对应时间
                const logEntry = order.statusLogs?.find((l) => l.toStatus === step.status);

                return (
                  <div key={step.status} className={styles.transfers__timelineStep}>
                    <div
                      className={cn(
                        styles.transfers__timelineDot,
                        dotStyle && styles[`transfers__timelineDot--${dotStyle}`],
                      )}
                    >
                      {dotStyle === 'completed' ? '\u2713' : dotStyle === 'failed' ? '\u2717' : ''}
                    </div>
                    <div className={styles.transfers__timelineContent}>
                      <div className={styles.transfers__timelineLabel}>{step.label}</div>
                      {logEntry && (
                        <div className={styles.transfers__timelineTime}>
                          {formatDateTime(logEntry.createdAt)}
                        </div>
                      )}
                    </div>
                  </div>
                );
              })}
            </div>
          </div>
        </div>

        {/* 状态变更日志 */}
        {order.statusLogs && order.statusLogs.length > 0 && (
          <div className={styles.transfers__section}>
            <h2 className={styles.transfers__sectionTitle}>状态变更日志</h2>
            <div className={styles.transfers__card}>
              <table className={styles.transfers__table}>
                <thead>
                  <tr>
                    <th>从状态</th>
                    <th>到状态</th>
                    <th>原因</th>
                    <th>时间</th>
                  </tr>
                </thead>
                <tbody>
                  {order.statusLogs.map((log) => (
                    <tr key={log.id}>
                      <td>{STATUS_LABEL[log.fromStatus] || log.fromStatus}</td>
                      <td>{STATUS_LABEL[log.toStatus] || log.toStatus}</td>
                      <td>{log.reason || '-'}</td>
                      <td>{formatDateTime(log.createdAt)}</td>
                    </tr>
                  ))}
                </tbody>
              </table>
            </div>
          </div>
        )}

        {/* 强制取消操作 */}
        {!isTerminal && (
          <div className={styles.transfers__actions}>
            {!showCancelConfirm ? (
              <button
                className={styles.transfers__cancelBtn}
                onClick={() => setShowCancelConfirm(true)}
              >
                强制取消
              </button>
            ) : (
              <div style={{ display: 'flex', gap: 12, alignItems: 'center' }}>
                <input
                  type="text"
                  placeholder="取消原因（必填）"
                  value={cancelReason}
                  onChange={(e) => setCancelReason(e.target.value)}
                  style={{
                    padding: '8px 12px',
                    border: '1px solid #ff4d4f',
                    borderRadius: 8,
                    fontSize: 14,
                    width: 280,
                  }}
                />
                <button
                  className={styles.transfers__cancelBtn}
                  onClick={handleForceCancel}
                  disabled={!cancelReason.trim() || forceCancel.isPending}
                >
                  {forceCancel.isPending ? '取消中...' : '确认取消'}
                </button>
                <Button
                  variant="outline"
                  size="sm"
                  onClick={() => {
                    setShowCancelConfirm(false);
                    setCancelReason('');
                  }}
                >
                  放弃
                </Button>
              </div>
            )}
          </div>
        )}
      </div>
    </PageContainer>
  );
}

/**
 * 状态名转样式类后缀
 */
function statusToStyle(status: string): string {
  const map: Record<string, string> = {
    PENDING: 'pending',
    SELLER_CONFIRMED: 'sellerConfirmed',
    PAYMENT_FROZEN: 'paymentFrozen',
    TREES_LOCKED: 'treesLocked',
    OWNERSHIP_TRANSFERRED: 'ownershipTransferred',
    CONTRIBUTION_ADJUSTED: 'contributionAdjusted',
    STATS_UPDATED: 'statsUpdated',
    PAYMENT_SETTLED: 'paymentSettled',
    COMPLETED: 'completed',
    CANCELLED: 'cancelled',
    FAILED: 'failed',
    ROLLING_BACK: 'rollingBack',
    ROLLED_BACK: 'rolledBack',
  };
  return map[status] || '';
}
