"use client";

import { useEffect, useMemo, useState } from "react";
import { useTranslations } from "next-intl";
import { Button } from "@/shared/components/ui/button";
import { X, Printer } from "lucide-react";
import { FocusTrap } from "@/shared/components/a11y/focus-trap";
import { flattenLessonPlanForPrint, type ExportVariant, type PrintableLessonPlan } from "../lib/export";
import type { LessonPlan } from "../types";

interface Props {
  plan: LessonPlan;
  textbookTitle?: string;
  chapterTitle?: string;
  teacherName?: string;
  className?: string;
  onClose: () => void;
}

/**
 * V5-4：打印视图组件
 *
 * 渲染扁平化后的 PrintableLessonPlan，提供"详细版/简洁版"切换。
 * 点击"打印"按钮调用 window.print()，通过浏览器原生能力保存为 PDF。
 * 使用 print: CSS 媒体查询隐藏工具栏，仅打印教学环节内容。
 */
export function PrintView({
  plan,
  textbookTitle,
  chapterTitle,
  teacherName,
  className,
  onClose,
}: Props) {
  const t = useTranslations("lessonPreparation");
  const [variant, setVariant] = useState<ExportVariant>("detailed");

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

  const printable = useMemo<PrintableLessonPlan>(
    () =>
      flattenLessonPlanForPrint(
        plan,
        { textbookTitle, chapterTitle, teacherName, className },
        variant,
      ),
    [plan, textbookTitle, chapterTitle, teacherName, className, variant],
  );

  function handlePrint() {
    window.print();
  }

  return (
    <div className="fixed inset-0 z-50 bg-black/30 flex items-center justify-center print:static print:bg-white print:p-0">
      <div
        role="dialog"
        aria-modal="true"
        aria-label={t("export.title")}
        className="bg-surface rounded-lg shadow-xl w-[800px] max-h-[90vh] flex flex-col print:static print:w-full print:max-h-none print:rounded-none print:shadow-none"
      >
        <FocusTrap className="contents">
          {/* 工具栏：print 时隐藏 */}
          <div className="flex justify-between items-center p-4 border-b print:hidden">
            <div className="flex items-center gap-3">
              <h3 className="font-title-md">{t("export.title")}</h3>
              <div className="flex items-center gap-1 text-sm">
                <button
                  className={`px-2 py-0.5 rounded ${variant === "detailed" ? "bg-primary text-on-primary" : "bg-surface-container-high"}`}
                  onClick={() => setVariant("detailed")}
                  aria-pressed={variant === "detailed"}
                >
                  {t("export.variantDetailed")}
                </button>
                <button
                  className={`px-2 py-0.5 rounded ${variant === "concise" ? "bg-primary text-on-primary" : "bg-surface-container-high"}`}
                  onClick={() => setVariant("concise")}
                  aria-pressed={variant === "concise"}
                >
                  {t("export.variantConcise")}
                </button>
              </div>
            </div>
            <div className="flex items-center gap-2">
              <Button size="sm" onClick={handlePrint}>
                <Printer className="w-4 h-4 mr-1" /> {t("export.print")}
              </Button>
              <button onClick={onClose} aria-label={t("action.close")}>
                <X className="w-4 h-4" aria-hidden="true" />
              </button>
            </div>
          </div>

          {/* 打印内容主体 */}
          <div className="p-8 overflow-y-auto flex-1 print:overflow-visible">
            {/* 页眉 */}
            <div className="border-b-2 border-on-surface pb-2 mb-4">
              <h1 className="text-2xl font-bold text-center">
                {printable.meta.planTitle}
              </h1>
              <div className="flex justify-between text-sm text-on-surface-variant mt-2">
                <span>
                  {printable.meta.textbookTitle && `${printable.meta.textbookTitle}`}
                  {printable.meta.chapterTitle && ` · ${printable.meta.chapterTitle}`}
                </span>
                <span>
                  {printable.meta.teacherName && `${t("export.teacher")}: ${printable.meta.teacherName}`}
                  {printable.meta.className && ` · ${t("export.class")}: ${printable.meta.className}`}
                </span>
              </div>
              <div className="text-xs text-on-surface-variant mt-1 text-right">
                {t("export.totalDuration", { count: printable.meta.totalDurationMin })}
                {printable.meta.lastSavedAt &&
                  ` · ${t("export.lastSavedAt")}: ${new Date(printable.meta.lastSavedAt).toLocaleString()}`}
              </div>
            </div>

            {/* 课文正文 */}
            {printable.textbookContent && (
              <section className="mb-6">
                <h2 className="text-lg font-semibold border-l-4 border-primary pl-2 mb-2">
                  {t("editor.textbookContent")}
                </h2>
                <div className="text-sm whitespace-pre-wrap leading-relaxed">
                  {printable.textbookContent}
                </div>
              </section>
            )}

            {/* 教学环节列表 */}
            {printable.sections.length === 0 ? (
              <p className="text-center text-on-surface-variant py-8">
                {t("export.empty")}
              </p>
            ) : (
              printable.sections.map((section, idx) => (
                <section key={`${section.type}-${idx}`} className="mb-4 break-inside-avoid">
                  <h2 className="text-lg font-semibold border-l-4 border-primary pl-2 mb-2">
                    {idx + 1}. {section.title}
                  </h2>
                  <div className="pl-4 space-y-1">
                    {section.lines.length === 0 ? (
                      <p className="text-sm text-on-surface-variant italic">
                        {t("export.emptySection")}
                      </p>
                    ) : (
                      section.lines.map((line, i) => (
                        <p key={i} className="text-sm leading-relaxed">
                          {line}
                        </p>
                      ))
                    )}
                  </div>
                </section>
              ))
            )}

            {/* 页脚 */}
            <div className="border-t border-outline-variant mt-8 pt-2 text-xs text-on-surface-variant text-center print:fixed print:bottom-2 print:left-0 print:right-0">
              {t("export.footerHint", { variant: t(`export.variant${variant === "detailed" ? "Detailed" : "Concise"}`) })}
            </div>
          </div>
        </FocusTrap>
      </div>
    </div>
  );
}
