"use client";

import { useMemo } from "react";
import { useTranslations } from "next-intl";
import { Plus, Minus, Pencil, Check } from "lucide-react";
import type { LessonPlanDocument } from "../types";
import { diffDocuments, hasChanges, type NodeDiff } from "../lib/version-diff";
import { getNodeColor } from "../lib/node-summary";
import { cn } from "@/shared/lib/utils";

interface Props {
  oldDoc: LessonPlanDocument;
  newDoc: LessonPlanDocument;
  /** 旧版本号（用于标题展示） */
  oldVersionNo?: number;
}

/**
 * V5-16 T2：版本对比视图。
 *
 * 以列表形式展示两个版本文档的节点级差异，
 * 支持 added/removed/modified/unchanged 四种状态标记。
 */
export function VersionDiffView({ oldDoc, newDoc, oldVersionNo }: Props) {
  const t = useTranslations("lessonPreparation");

  const result = useMemo(() => diffDocuments(oldDoc, newDoc), [oldDoc, newDoc]);
  const changed = hasChanges(result);

  return (
    <div className="space-y-3">
      {/* 摘要条 */}
      <div className="flex items-center gap-3 text-xs flex-wrap">
        <span className="text-on-surface-variant">
          {t("diff.summary", {
            added: result.summary.added,
            removed: result.summary.removed,
            modified: result.summary.modified,
          })}
        </span>
        {oldVersionNo !== undefined && (
          <span className="text-on-surface-variant">
            {t("diff.comparing", { version: oldVersionNo })}
          </span>
        )}
      </div>

      {!changed ? (
        <div className="text-sm text-on-surface-variant p-3 rounded border border-outline-variant bg-surface-container-low">
          {t("diff.noChanges")}
        </div>
      ) : (
        <ul className="space-y-1.5">
          {result.diffs
            .filter((d) => d.type !== "unchanged")
            .map((d, idx) => (
              <DiffItem key={idx} diff={d} t={t} />
            ))}
        </ul>
      )}

      {/* unchanged 计数（折叠） */}
      {result.summary.unchanged > 0 && (
        <div className="text-xs text-on-surface-variant flex items-center gap-1">
          <Check className="w-3 h-3" aria-hidden="true" />
          {t("diff.unchangedCount", { count: result.summary.unchanged })}
        </div>
      )}
    </div>
  );
}

function DiffItem({
  diff,
  t,
}: {
  diff: NodeDiff;
  t: ReturnType<typeof useTranslations>;
}) {
  const node = diff.newNode ?? diff.oldNode;
  const color = node ? getNodeColor(node.type) : "#999";
  const title = node?.title || node?.type || "";

  const icon = {
    added: <Plus className="w-3.5 h-3.5 text-primary" aria-hidden="true" />,
    removed: <Minus className="w-3.5 h-3.5 text-error" aria-hidden="true" />,
    modified: <Pencil className="w-3.5 h-3.5 text-tertiary" aria-hidden="true" />,
    unchanged: <Check className="w-3.5 h-3.5 text-on-surface-variant" aria-hidden="true" />,
  }[diff.type];

  const label = t(`diff.${diff.type}`);

  return (
    <li
      className={cn(
        "flex items-start gap-2 px-2.5 py-1.5 rounded border text-sm",
        diff.type === "added" && "border-primary/40 bg-primary-container/20",
        diff.type === "removed" && "border-error/40 bg-error-container/20",
        diff.type === "modified" && "border-tertiary/40 bg-tertiary-container/20",
      )}
    >
      <span
        className="inline-block w-2 h-2 rounded-full mt-1.5 flex-shrink-0"
        style={{ backgroundColor: color }}
        aria-hidden="true"
      />
      {icon}
      <div className="flex-1 min-w-0">
        <div className="flex items-center gap-2">
          <span className="text-[10px] px-1.5 py-0.5 rounded bg-surface-container-highest font-medium flex-shrink-0">
            {label}
          </span>
          <span className="truncate font-medium">{title}</span>
        </div>
        {diff.type === "modified" && diff.changedFields && diff.changedFields.length > 0 && (
          <div className="text-xs text-on-surface-variant mt-0.5">
            {t("diff.changedFields")}:{" "}
            {diff.changedFields.map((f) => t(`diff.field.${f}`)).join(", ")}
          </div>
        )}
      </div>
    </li>
  );
}
