"use client";

import { useEffect, useMemo } from "react";
import { useTranslations } from "next-intl";
import { X, AlertTriangle, CheckCircle2 } from "lucide-react";
import { FocusTrap } from "@/shared/components/a11y/focus-trap";
import type { LessonPlanDocument } from "../types";
import { checkConsistency, hasConsistencyWarnings, type ConsistencyIssue } from "../lib/consistency-check";
import { cn } from "@/shared/lib/utils";

interface Props {
  doc: LessonPlanDocument;
  onClose: () => void;
}

/**
 * V5-19 T3：教学评一致性校验对话框。
 *
 * 以纯函数 `checkConsistency` 计算结果，仅做 UI 展示。
 * 不修改文档，不阻断保存。
 */
export function ConsistencyCheckDialog({ doc, onClose }: Props) {
  const t = useTranslations("lessonPreparation");

  const result = useMemo(() => checkConsistency(doc), [doc]);
  const hasWarnings = hasConsistencyWarnings(result);

  // ESC 关闭
  useEffect(() => {
    function handleEsc(e: KeyboardEvent) {
      if (e.key === "Escape") onClose();
    }
    document.addEventListener("keydown", handleEsc);
    return () => document.removeEventListener("keydown", handleEsc);
  }, [onClose]);

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/30">
      <div
        role="dialog"
        aria-modal="true"
        aria-label={t("consistency.title")}
        className="bg-surface rounded-lg shadow-xl w-[520px] max-h-[80vh] flex flex-col"
      >
        <FocusTrap className="contents">
          <div className="flex justify-between items-center p-4 border-b border-outline-variant">
            <h3 className="font-title-md flex items-center gap-2">
              <AlertTriangle className="w-4 h-4 text-primary" aria-hidden="true" />
              {t("consistency.title")}
            </h3>
            <button onClick={onClose} aria-label={t("editor.consistencyClose")}>
              <X className="w-4 h-4" aria-hidden="true" />
            </button>
          </div>

          <div className="p-4 overflow-y-auto space-y-4">
            {/* 顶部统计 */}
            <div className="grid grid-cols-3 gap-2 text-center">
              <div className="rounded border border-outline-variant p-2">
                <div className="text-xs text-on-surface-variant">
                  {t("editor.consistencyObjectiveCount", { count: result.objectiveCount })}
                </div>
              </div>
              <div className="rounded border border-outline-variant p-2">
                <div className="text-xs text-on-surface-variant">
                  {t("editor.consistencyExerciseCount", { count: result.exerciseCount })}
                </div>
              </div>
              <div className="rounded border border-outline-variant p-2">
                <div className="text-xs text-on-surface-variant">
                  {t("consistency.coverage", {
                    covered: result.coveredObjectiveCount,
                    total: result.objectiveCount,
                  })}
                </div>
              </div>
            </div>

            {/* 一致性分数 */}
            <div className="flex items-center justify-between rounded border border-outline-variant p-3">
              <span className="text-sm font-medium">{t("consistency.score", { score: result.score })}</span>
              <span
                className={cn(
                  "text-xs px-2 py-0.5 rounded font-medium",
                  result.score >= 80
                    ? "bg-primary-container text-on-primary-container"
                    : result.score >= 50
                      ? "bg-secondary-container text-on-secondary-container"
                      : "bg-error-container text-on-error-container",
                )}
              >
                {result.score}
              </span>
            </div>

            {/* 问题列表 */}
            <div>
              <div className="text-xs font-medium text-on-surface-variant mb-2">
                {hasWarnings ? t("consistency.title") : t("consistency.noIssues")}
              </div>
              {hasWarnings ? (
                <ul className="space-y-1.5">
                  {result.issues.map((issue, idx) => (
                    <IssueItem key={`${issue.code}-${idx}`} issue={issue} t={t} />
                  ))}
                </ul>
              ) : (
                <div className="flex items-center gap-2 text-sm text-on-surface-variant p-3 rounded border border-outline-variant bg-surface-container-low">
                  <CheckCircle2 className="w-4 h-4 text-primary" aria-hidden="true" />
                  {t("consistency.noIssues")}
                </div>
              )}
            </div>
          </div>

          <div className="p-3 border-t border-outline-variant flex justify-end">
            <button
              onClick={onClose}
              className="text-sm px-3 py-1.5 rounded border border-outline-variant hover:bg-surface-container-low"
            >
              {t("editor.consistencyClose")}
            </button>
          </div>
        </FocusTrap>
      </div>
    </div>
  );
}

function IssueItem({
  issue,
  t,
}: {
  issue: ConsistencyIssue;
  t: ReturnType<typeof useTranslations>;
}) {
  const isWarning = issue.severity === "warning";
  const message = t(`consistency.code.${issue.code}`, {
    title: issue.params?.title ?? issue.nodeTitle ?? "",
  });
  return (
    <li
      className={cn(
        "flex items-start gap-2 px-2 py-1.5 rounded border text-sm",
        isWarning
          ? "border-error/40 bg-error-container/30"
          : "border-outline-variant bg-surface-container-low",
      )}
    >
      <AlertTriangle
        className={cn("w-3.5 h-3.5 mt-0.5 flex-shrink-0", isWarning ? "text-error" : "text-on-surface-variant")}
        aria-hidden="true"
      />
      <span className="flex-1">{message}</span>
    </li>
  );
}
