"use client";

import { useEffect, useMemo, useState } from "react";
import { useTranslations } from "next-intl";
import { useLessonPlanContextSafe, useLessonPlanTrackerSafe } from "../providers/lesson-plan-provider";
import { Button } from "@/shared/components/ui/button";
import { FocusTrap } from "@/shared/components/a11y/focus-trap";
import { X, ChevronRight, ChevronLeft, CheckCircle2 } from "lucide-react";
import type { ExerciseItem } from "../types";
import { isRecord } from "@/shared/lib/type-guards";

interface Props {
  planId: string;
  blockId: string;
  classes: { id: string; name: string }[];
  /** V5-3：题目列表（从 exercise-block 传入，用于预览步骤）*/
  items: ExerciseItem[];
  onClose: () => void;
  onPublished: () => void;
}

type Step = "select" | "preview" | "confirm";

/** V5-3：从 inline 题目内容中安全提取题干预览文本 */
function extractStemPreview(content: unknown): string {
  if (!isRecord(content)) return "";
  const stem = content.stem;
  if (typeof stem === "string") return stem.slice(0, 80);
  const text = content.text;
  if (typeof text === "string") return text.slice(0, 80);
  return "";
}

/** V5-3：题型 i18n 键映射 */
function questionTypeKey(type: string): string {
  const known = ["single_choice", "multiple_choice", "true_false", "short_answer", "essay", "text", "judgment"];
  return known.includes(type) ? `questionBank.type.${type}` : "questionBank.type.single_choice";
}

export function PublishHomeworkDialog({
  planId,
  blockId,
  classes,
  items,
  onClose,
  onPublished,
}: Props) {
  const t = useTranslations("lessonPreparation");
  const ctx = useLessonPlanContextSafe();
  const service = ctx?.service ?? null;
  const tracker = useLessonPlanTrackerSafe();
  const [step, setStep] = useState<Step>("select");
  const [selectedClasses, setSelectedClasses] = useState<string[]>([]);
  const [availableAt, setAvailableAt] = useState("");
  const [dueAt, setDueAt] = useState("");
  const [error, setError] = useState<string | null>(null);
  const [loading, setLoading] = useState(false);

  // P1-1 修复：ESC 键关闭对话框
  useEffect(() => {
    function handleEsc(e: KeyboardEvent) {
      if (e.key === "Escape") onClose();
    }
    document.addEventListener("keydown", handleEsc);
    return () => document.removeEventListener("keydown", handleEsc);
  }, [onClose]);

  // V5-3：计算总分
  const totalScore = useMemo(
    () => items.reduce((sum, it) => sum + (it.score ?? 0), 0),
    [items],
  );

  // V5-3：选中的班级数
  const selectedClassCount = selectedClasses.length;

  function handleSelectClass(classId: string) {
    setSelectedClasses((prev) =>
      prev.includes(classId) ? prev.filter((x) => x !== classId) : [...prev, classId],
    );
  }

  function handleNextFromSelect() {
    if (selectedClasses.length === 0) {
      setError(t("publish.selectClass"));
      return;
    }
    setError(null);
    setStep("preview");
  }

  function handleNextFromPreview() {
    setStep("confirm");
  }

  function handleBackToSelect() {
    setStep("select");
  }

  function handleBackToPreview() {
    setStep("preview");
  }

  async function handlePublish() {
    if (!service) return;
    setLoading(true);
    setError(null);
    try {
      const res = await service.publishLessonPlanHomework({
        planId,
        blockId,
        classIds: selectedClasses,
        availableAt: availableAt || undefined,
        dueAt: dueAt || undefined,
      });
      if (res.success) {
        tracker.track("lesson_plan.publish", {
          planId,
          blockId,
          classCount: selectedClasses.length,
        });
        onPublished();
        onClose();
      } else {
        setError(res.message ?? t("error.publish"));
      }
    } catch (e) {
      console.error("[PublishHomeworkDialog] publish failed", e);
      setError(t("error.publish"));
    } finally {
      setLoading(false);
    }
  }

  // V5-3：步骤指示器文案
  const stepLabel =
    step === "select"
      ? t("publish.step1")
      : step === "preview"
        ? t("publish.step2")
        : t("publish.step3");
  const stepNumber = step === "select" ? 1 : step === "preview" ? 2 : 3;

  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("publish.title")}
        className="bg-surface rounded-lg shadow-xl w-[640px] max-h-[90vh] flex flex-col"
      >
        <FocusTrap className="contents">
          <div className="flex justify-between items-center p-4 border-b">
            <div className="flex items-center gap-2">
              <h3 className="font-title-md">{t("publish.title")}</h3>
              <span className="text-xs text-on-surface-variant">
                {t("publish.stepIndicator", { current: stepNumber, total: 3, label: stepLabel })}
              </span>
            </div>
            <button onClick={onClose} aria-label={t("action.close")}>
              <X className="w-4 h-4" aria-hidden="true" />
            </button>
          </div>

          <div className="p-4 space-y-3 overflow-y-auto flex-1">
            {/* 步骤 1：选班级 + 时间 */}
            {step === "select" && (
              <>
                <div>
                  <label className="text-sm font-medium">{t("publish.classLabel")}</label>
                  <div className="mt-1 space-y-1 max-h-40 overflow-y-auto">
                    {classes.map((c) => (
                      <label key={c.id} className="flex items-center gap-2">
                        <input
                          type="checkbox"
                          checked={selectedClasses.includes(c.id)}
                          onChange={() => handleSelectClass(c.id)}
                        />
                        <span className="text-sm">{c.name}</span>
                      </label>
                    ))}
                  </div>
                </div>
                <div>
                  <label className="text-sm font-medium">
                    {t("publish.availableAtLabel")}
                  </label>
                  <input
                    type="datetime-local"
                    value={availableAt}
                    onChange={(e) => setAvailableAt(e.target.value)}
                    className="w-full border rounded px-2 py-1 mt-1"
                  />
                </div>
                <div>
                  <label className="text-sm font-medium">
                    {t("publish.dueAtLabel")}
                  </label>
                  <input
                    type="datetime-local"
                    value={dueAt}
                    onChange={(e) => setDueAt(e.target.value)}
                    className="w-full border rounded px-2 py-1 mt-1"
                  />
                </div>
                {error && <p className="text-error text-sm">{error}</p>}
              </>
            )}

            {/* 步骤 2：预览题目 + 总分 + 班级 */}
            {step === "preview" && (
              <>
                <div className="bg-surface-container-high rounded p-3 text-sm space-y-1">
                  <div>
                    {t("publish.previewClassCount")}: <strong>{selectedClassCount}</strong>
                  </div>
                  <div>
                    {t("publish.previewQuestionCount")}: <strong>{items.length}</strong>
                  </div>
                  <div>
                    {t("publish.previewTotalScore")}: <strong>{totalScore}</strong>
                  </div>
                </div>
                <div>
                  <label className="text-sm font-medium block mb-2">
                    {t("publish.previewQuestionList")}
                  </label>
                  <ol className="space-y-2 list-decimal list-inside text-sm">
                    {items.map((item, idx) => (
                      <li
                        key={`${item.questionId}-${idx}`}
                        className="border border-outline-variant rounded p-2"
                      >
                        <div className="flex justify-between items-start gap-2">
                          <div className="flex-1">
                            <div className="text-xs text-on-surface-variant">
                              {t(questionTypeKey(item.inlineContent?.type ?? "single_choice"))} · {t("publish.previewSource", { source: t(`questionBank.source.${item.source}`) })}
                            </div>
                            {item.source === "inline" && item.inlineContent ? (
                              <div className="mt-1 text-sm">
                                {extractStemPreview(item.inlineContent.content) || t("publish.previewNoStem")}
                              </div>
                            ) : (
                              <div className="mt-1 text-sm font-mono text-xs">
                                ID: {item.questionId}
                              </div>
                            )}
                          </div>
                          <span className="text-xs bg-surface-container-highest px-2 py-0.5 rounded">
                            {t("publish.previewScore", { score: item.score })}
                          </span>
                        </div>
                      </li>
                    ))}
                  </ol>
                </div>
              </>
            )}

            {/* 步骤 3：确认发布 */}
            {step === "confirm" && (
              <div className="space-y-3">
                <div className="flex items-center gap-2 text-sm">
                  <CheckCircle2 className="w-5 h-5 text-primary" />
                  <span className="font-medium">{t("publish.confirmTitle")}</span>
                </div>
                <div className="bg-surface-container-high rounded p-3 text-sm space-y-1">
                  <div>{t("publish.confirmClassCount", { count: selectedClassCount })}</div>
                  <div>{t("publish.confirmQuestionCount", { count: items.length })}</div>
                  <div>{t("publish.confirmTotalScore", { score: totalScore })}</div>
                  {availableAt && (
                    <div>{t("publish.confirmAvailableAt", { time: availableAt })}</div>
                  )}
                  {dueAt && (
                    <div>{t("publish.confirmDueAt", { time: dueAt })}</div>
                  )}
                </div>
                <p className="text-xs text-on-surface-variant">
                  {t("publish.confirmWarning")}
                </p>
                {error && <p className="text-error text-sm">{error}</p>}
              </div>
            )}
          </div>

          {/* 步骤导航按钮 */}
          <div className="p-4 border-t flex justify-between gap-2">
            {step === "select" && (
              <>
                <Button variant="outline" onClick={onClose}>
                  {t("action.cancel")}
                </Button>
                <Button onClick={handleNextFromSelect}>
                  {t("publish.next")} <ChevronRight className="w-4 h-4 ml-1" />
                </Button>
              </>
            )}
            {step === "preview" && (
              <>
                <Button variant="outline" onClick={handleBackToSelect}>
                  <ChevronLeft className="w-4 h-4 mr-1" /> {t("publish.back")}
                </Button>
                <Button onClick={handleNextFromPreview}>
                  {t("publish.next")} <ChevronRight className="w-4 h-4 ml-1" />
                </Button>
              </>
            )}
            {step === "confirm" && (
              <>
                <Button variant="outline" onClick={handleBackToPreview} disabled={loading}>
                  <ChevronLeft className="w-4 h-4 mr-1" /> {t("publish.back")}
                </Button>
                <Button onClick={handlePublish} disabled={loading}>
                  {loading ? t("publish.publishing") : t("publish.publish")}
                </Button>
              </>
            )}
          </div>
        </FocusTrap>
      </div>
    </div>
  );
}
