"use client";

/**
 * TeacherAnnotationOverlay — 教师批注覆盖层（ai14，P5）
 *
 * 在学生答案上方展示教师的批注信息：
 * - 批注类型：comment（评论）/ highlight（高亮）/ correction（纠错）
 * - 每条批注包含：教师名、批注内容、批注时间
 * - 支持折叠/展开
 *
 * 用于 my-exams/[id]/result 页面，展示教师对学生作答的反馈。
 */

import { useState, useCallback } from "react";
import { cn } from "@/lib/exam-types";

/** 批注类型 */
export type AnnotationType = "comment" | "highlight" | "correction";

/** 教师批注数据 */
export interface TeacherAnnotation {
  /** 批注 ID */
  id: string;
  /** 关联题目 ID */
  questionId: string;
  /** 批注类型 */
  type: AnnotationType;
  /** 教师姓名 */
  teacherName: string;
  /** 批注内容 */
  content: string;
  /** 批注时间（ISO 8601） */
  createdAt: string;
  /** 高亮起始位置（字符偏移，仅 highlight 类型） */
  startOffset?: number;
  /** 高亮结束位置（字符偏移，仅 highlight 类型） */
  endOffset?: number;
}

export interface TeacherAnnotationOverlayProps {
  /** 当前题目 ID */
  questionId: string;
  /** 学生答案文本（用于高亮定位） */
  answerText?: string;
  /** 该题目的批注列表 */
  annotations: TeacherAnnotation[];
  /** 默认展开（默认 true） */
  defaultExpanded?: boolean;
}

const TYPE_LABEL: Record<AnnotationType, string> = {
  comment: "评论",
  highlight: "高亮",
  correction: "纠错",
};

/** 批注类型对应的颜色令牌 */
function typeColorVar(type: AnnotationType): string {
  switch (type) {
    case "correction":
      return "var(--color-danger)";
    case "highlight":
      return "var(--color-warning)";
    case "comment":
    default:
      return "var(--color-info)";
  }
}

/** 批注类型对应的 badge 类名 */
function typeBadgeClass(type: AnnotationType): string {
  switch (type) {
    case "correction":
      return "badge-danger";
    case "highlight":
      return "badge-warning";
    case "comment":
    default:
      return "badge-info";
  }
}

/** 格式化日期 */
function formatDate(iso: string): string {
  try {
    return new Date(iso).toLocaleString("zh-CN", {
      month: "2-digit",
      day: "2-digit",
      hour: "2-digit",
      minute: "2-digit",
    });
  } catch {
    return iso;
  }
}

/** 渲染带高亮的答案文本 */
function renderHighlightedText(
  text: string,
  annotations: TeacherAnnotation[],
): React.ReactNode {
  if (!text) return null;
  const highlights = annotations
    .filter(
      (a) =>
        a.type === "highlight" &&
        a.startOffset !== undefined &&
        a.endOffset !== undefined,
    )
    .sort((a, b) => (a.startOffset ?? 0) - (b.startOffset ?? 0));

  if (highlights.length === 0) {
    return <span style={{ color: "var(--color-ink)" }}>{text}</span>;
  }

  const parts: React.ReactNode[] = [];
  let cursor = 0;
  highlights.forEach((hl, idx) => {
    const start = hl.startOffset ?? 0;
    const end = hl.endOffset ?? text.length;
    if (start > cursor) {
      parts.push(
        <span key={`text-${idx}`} style={{ color: "var(--color-ink)" }}>
          {text.slice(cursor, start)}
        </span>,
      );
    }
    parts.push(
      <mark
        key={`hl-${idx}`}
        className="rounded-sm px-xs"
        style={{
          background: "var(--color-accent-muted)",
          color: "var(--color-ink)",
        }}
        title={hl.content}
      >
        {text.slice(start, end)}
      </mark>,
    );
    cursor = end;
  });
  if (cursor < text.length) {
    parts.push(
      <span key="text-end" style={{ color: "var(--color-ink)" }}>
        {text.slice(cursor)}
      </span>,
    );
  }
  return parts;
}

export function TeacherAnnotationOverlay({
  questionId,
  answerText,
  annotations,
  defaultExpanded = true,
}: TeacherAnnotationOverlayProps): JSX.Element | null {
  const [expanded, setExpanded] = useState(defaultExpanded);
  const toggle = useCallback((): void => setExpanded((v) => !v), []);

  // 筛选当前题目的批注
  const questionAnnotations = annotations.filter(
    (a) => a.questionId === questionId,
  );

  if (questionAnnotations.length === 0) return null;

  const hasHighlight = questionAnnotations.some((a) => a.type === "highlight");
  const nonHighlightAnnotations = questionAnnotations.filter(
    (a) => a.type !== "highlight",
  );

  return (
    <section
      className="mt-md mark-left"
      aria-label="教师批注"
      role="region"
    >
      {/* 标题栏 */}
      <div className="flex items-center justify-between">
        <h4
          className="font-serif text-sm flex items-center gap-sm"
          style={{ color: "var(--color-ink)" }}
        >
          <svg
            width="14"
            height="14"
            viewBox="0 0 24 24"
            fill="none"
            stroke="currentColor"
            strokeWidth="2"
            aria-hidden="true"
            style={{ color: "var(--color-accent)" }}
          >
            <path d="M11 4H4a2 2 0 0 0-2 2v14a2 2 0 0 0 2 2h14a2 2 0 0 0 2-2v-7" />
            <path d="M18.5 2.5a2.121 2.121 0 0 1 3 3L12 15l-4 1 1-4 9.5-9.5z" />
          </svg>
          教师批注
          <span
            className="badge badge-info"
            aria-label={`共 ${questionAnnotations.length} 条批注`}
          >
            {questionAnnotations.length}
          </span>
        </h4>
        <button
          type="button"
          onClick={toggle}
          className="text-xs"
          style={{ color: "var(--color-ink-muted)" }}
          aria-expanded={expanded}
          aria-controls={`annotation-detail-${questionId}`}
        >
          {expanded ? "收起" : "展开"}
        </button>
      </div>

      {expanded && (
        <div
          id={`annotation-detail-${questionId}`}
          className="mt-sm space-y-sm"
        >
          {/* 高亮答案文本 */}
          {hasHighlight && answerText && (
            <div
              className="p-sm rounded text-sm leading-relaxed"
              style={{
                background: "var(--color-paper)",
                border: "1px solid var(--color-rule)",
              }}
            >
              {renderHighlightedText(answerText, questionAnnotations)}
            </div>
          )}

          {/* 批注列表 */}
          {nonHighlightAnnotations.map((annotation) => (
            <div
              key={annotation.id}
              className={cn(
                "p-sm rounded border",
                annotation.type === "correction"
                  ? "border-rule"
                  : "border-rule",
              )}
              style={{
                borderLeft: `2px solid ${typeColorVar(annotation.type)}`,
                background: "var(--color-paper)",
              }}
            >
              <div className="flex items-center gap-sm mb-xs">
                <span
                  className={cn("badge", typeBadgeClass(annotation.type))}
                >
                  {TYPE_LABEL[annotation.type]}
                </span>
                <span
                  className="text-xs"
                  style={{ color: "var(--color-ink-muted)" }}
                >
                  {annotation.teacherName}
                </span>
                <span
                  className="text-xs ml-auto"
                  style={{ color: "var(--color-ink-subtle)" }}
                >
                  {formatDate(annotation.createdAt)}
                </span>
              </div>
              <p
                className="text-sm"
                style={{ color: "var(--color-ink)" }}
              >
                {annotation.content}
              </p>
            </div>
          ))}
        </div>
      )}
    </section>
  );
}
