/**
 * 查重详情页面 — V21 设计系统
 * 风险评估 + 基本信息 + 检测项列表 + 匹配片段
 * 零 antd 依赖
 */
import React, { useState, useCallback } from "react";
import { useQuery, useMutation, useQueryClient } from "@tanstack/react-query";
import { Button, Tag, Tooltip } from "@/components/ui";
import { useParams, useNavigate } from "react-router-dom";
import {
  getDuplicationDetail,
  retryDuplication,
  type DuplicateSegment,
} from "@/api/duplication";
import "./duplication.css";
import PageHead from "@/components/layout/PageHead";

/** 格式化时间（秒 → mm:ss） */
const formatTime = (seconds: number) => {
  const m = Math.floor(seconds / 60);
  const s = Math.floor(seconds % 60);
  return `${m.toString().padStart(2, "0")}:${s.toString().padStart(2, "0")}`;
};

/** 格式化文件大小 */
const formatSize = (bytes: number) => {
  if (bytes < 1024 * 1024) return `${(bytes / 1024).toFixed(0)} KB`;
  if (bytes < 1024 * 1024 * 1024)
    return `${(bytes / 1024 / 1024).toFixed(1)} MB`;
  return `${(bytes / 1024 / 1024 / 1024).toFixed(2)} GB`;
};

/** 格式化时长 */
const formatDuration = (seconds?: number) => {
  if (!seconds) return "-";
  const m = Math.floor(seconds / 60);
  const s = seconds % 60;
  return m > 0 ? `${m}分${s}秒` : `${s}秒`;
};

/** 根据查重率获取风险等级 */
const getRiskLevel = (rate?: number): "low" | "medium" | "high" => {
  if (rate === undefined) return "low";
  if (rate <= 10) return "low";
  if (rate <= 30) return "medium";
  return "high";
};

/** 风险等级描述 */
const RISK_DESC: Record<string, string> = {
  low: "查重率较低，内容原创度高",
  medium: "存在一定重复，建议修改部分片段",
  high: "重复率较高，建议大幅修改或替换",
};

/** 风险等级标签变体 */
const RISK_TAG_VARIANT: Record<string, "success" | "warning" | "error"> = {
  low: "success",
  medium: "warning",
  high: "error",
};

/** 风险等级文字 */
const RISK_LABEL: Record<string, string> = {
  low: "低风险",
  medium: "中风险",
  high: "高风险",
};

/** 简易 toast */
interface ToastState {
  message: string;
  type: "success" | "error" | "warning";
}

/** 单个重复片段卡片 */
const SegmentCard: React.FC<{ segment: DuplicateSegment; index: number }> = ({
  segment,
  index,
}) => {
  const sourceDuration = segment.source_end - segment.source_start;
  const matchedDuration = segment.matched_end - segment.matched_start;
  const riskLevel =
    segment.similarity >= 90
      ? "high"
      : segment.similarity >= 70
        ? "medium"
        : "low";

  return (
    <div className="dup-check-item">
      <div className="dup-check-icon">🎬</div>
      <div className="dup-check-body">
        <h4>
          片段 {index + 1}：{segment.matched_video_name}
        </h4>
        <p>
          原始 {formatTime(segment.source_start)} -{" "}
          {formatTime(segment.source_end)}（{sourceDuration.toFixed(0)}s）→ 匹配{" "}
          {formatTime(segment.matched_start)} -{" "}
          {formatTime(segment.matched_end)}（{matchedDuration.toFixed(0)}s）
        </p>
      </div>
      <div className={`dup-check-bar`}>
        <div
          className={`dup-check-bar-fill ${riskLevel}`}
          style={{ width: `${Math.min(segment.similarity, 100)}%` }}
        />
      </div>
      <span className={`dup-check-value ${riskLevel}`}>
        {segment.similarity.toFixed(1)}%
      </span>
    </div>
  );
};

const DuplicationDetail: React.FC = () => {
  const { id } = useParams<{ id: string }>();
  const navigate = useNavigate();
  const queryClient = useQueryClient();
  const [toast, setToast] = useState<ToastState | null>(null);

  const showToast = useCallback(
    (message: string, type: "success" | "error" | "warning") => {
      setToast({ message, type });
      setTimeout(() => setToast(null), 3000);
    },
    [],
  );

  const {
    data: detail,
    isLoading,
    isError,
  } = useQuery({
    queryKey: ["duplication-detail", id],
    queryFn: () => getDuplicationDetail(id!),
    enabled: !!id,
  });

  // 重新查重
  const retryMutation = useMutation({
    mutationFn: retryDuplication,
    onSuccess: () => {
      showToast("已重新提交查重", "success");
      queryClient.invalidateQueries({ queryKey: ["duplication-detail", id] });
    },
    onError: () => {
      showToast("重新查重失败", "error");
    },
  });

  if (isLoading) {
    return (
      <div className="dup-page">
        <div className="dup-results-empty">
          <div className="dup-results-empty-icon">⏳</div>
          <p>加载中...</p>
        </div>
      </div>
    );
  }

  if (isError || !detail) {
    return (
      <div className="dup-page">
        <div className="dup-results-empty">
          <div className="dup-results-empty-icon">😕</div>
          <p>{isError ? "加载查重记录失败" : "未找到查重记录"}</p>
          <Button
            buttonType="primary"
            buttonSize="md"
            onClick={() => navigate("/app/duplication/results")}
            style={{ marginTop: 16 }}
          >
            返回列表
          </Button>
        </div>
      </div>
    );
  }

  const riskLevel = getRiskLevel(detail.duplicate_rate);
  const similarityPercent =
    detail.duplicate_rate !== undefined
      ? detail.duplicate_rate.toFixed(1)
      : "—";

  return (
    <div className="dup-page">
      {/* Toast */}
      {toast && (
        <div className={`dup-toast dup-toast--${toast.type}`}>
          {toast.message}
        </div>
      )}

      <PageHead
        title={`🎬 ${detail.filename}`}
        description={
          <div
            className="dup-detail-header-meta"
            style={{
              display: "flex",
              gap: 12,
              alignItems: "center",
              marginTop: 8,
            }}
          >
            <Tag variant={RISK_TAG_VARIANT[riskLevel]}>
              {RISK_LABEL[riskLevel]}
            </Tag>
            <span>{formatSize(detail.file_size)}</span>
            <span>{formatDuration(detail.duration_seconds)}</span>
            <span>
              提交于 {new Date(detail.created_at).toLocaleString("zh-CN")}
            </span>
          </div>
        }
        actions={
          <div
            className="dup-detail-actions"
            style={{ display: "flex", gap: 8 }}
          >
            <Button
              buttonType="secondary"
              buttonSize="md"
              onClick={() => {
                showToast("报告下载功能开发中", "warning");
              }}
            >
              📥 下载报告
            </Button>
            {detail.status === "failed" && (
              <Button
                buttonType="primary"
                buttonSize="md"
                onClick={() => retryMutation.mutate(detail.id)}
              >
                🔄 重新查重
              </Button>
            )}
          </div>
        }
      />

      {/* 内容网格 */}
      <div className="dup-detail-grid">
        {/* 风险评估卡片 */}
        <div className="dup-risk-card">
          <h3>📊 风险评估</h3>
          <div className={`dup-risk-circle ${riskLevel}`}>
            <span className="dup-risk-value">{similarityPercent}%</span>
            <span className="dup-risk-label">查重率</span>
          </div>
          <p className="dup-risk-desc">{RISK_DESC[riskLevel]}</p>
        </div>

        {/* 基本信息卡片 */}
        <div className="dup-info-detail-card">
          <h3>📋 基本信息</h3>
          <div className="dup-info-rows">
            <div className="dup-info-row">
              <span className="dup-info-row-label">文件名</span>
              <Tooltip title={detail.filename}>
                <span
                  className="dup-info-row-value"
                  style={{
                    maxWidth: 200,
                    overflow: "hidden",
                    textOverflow: "ellipsis",
                    whiteSpace: "nowrap",
                  }}
                >
                  {detail.filename}
                </span>
              </Tooltip>
            </div>
            <div className="dup-info-row">
              <span className="dup-info-row-label">文件大小</span>
              <span className="dup-info-row-value">
                {formatSize(detail.file_size)}
              </span>
            </div>
            <div className="dup-info-row">
              <span className="dup-info-row-label">视频时长</span>
              <span className="dup-info-row-value">
                {formatDuration(detail.duration_seconds)}
              </span>
            </div>
            <div className="dup-info-row">
              <span className="dup-info-row-label">查重状态</span>
              <span className="dup-info-row-value">
                <Tag
                  variant={
                    detail.status === "completed"
                      ? "success"
                      : detail.status === "failed"
                        ? "error"
                        : detail.status === "processing"
                          ? "warning"
                          : "info"
                  }
                >
                  {detail.status === "completed"
                    ? "✅ 已完成"
                    : detail.status === "failed"
                      ? "❌ 失败"
                      : detail.status === "processing"
                        ? "🔄 查重中"
                        : "⏳ 等待中"}
                </Tag>
              </span>
            </div>
            <div className="dup-info-row">
              <span className="dup-info-row-label">重复片段数</span>
              <span className="dup-info-row-value">
                {detail.duplicate_count ?? 0} 个
              </span>
            </div>
            <div className="dup-info-row">
              <span className="dup-info-row-label">提交时间</span>
              <span className="dup-info-row-value">
                {new Date(detail.created_at).toLocaleString("zh-CN")}
              </span>
            </div>
          </div>
        </div>

        {/* 检测项列表 */}
        <div className="dup-checks-section">
          <h3>
            🔍 重复片段详情
            <Tag variant="primary" style={{ marginLeft: 8 }}>
              {detail.segments?.length ?? 0} 个片段
            </Tag>
          </h3>

          {detail.segments && detail.segments.length > 0 ? (
            <div className="dup-checks-list">
              {detail.segments.map((segment, index) => (
                <SegmentCard key={segment.id} segment={segment} index={index} />
              ))}
            </div>
          ) : (
            <div className="dup-results-empty" style={{ padding: "32px 0" }}>
              <div className="dup-results-empty-icon">🎉</div>
              <p>未发现重复片段，内容原创度很高</p>
            </div>
          )}
        </div>
      </div>
    </div>
  );
};

export default DuplicationDetail;
