"use client";

import { useState } from "react";
import { useTranslations } from "next-intl";
import { toast } from "sonner";
import { createId } from "@paralleldrive/cuid2";
import { Button } from "@/shared/components/ui/button";
import { FocusTrap } from "@/shared/components/a11y/focus-trap";
import { X, Tag } from "lucide-react";
import { KnowledgePointPicker } from "./knowledge-point-picker";
import { LessonPlanErrorBoundary } from "./lesson-plan-error-boundary";
import type { ExerciseItem, InlineQuestionContent } from "../types";
import { VALID_QUESTION_TYPES } from "../lib/type-guards";

interface Props {
  onAdd: (item: ExerciseItem) => void;
  onClose: () => void;
  textbookId?: string;
  chapterId?: string;
}

// V4 P1-10 修复：复用 lib/type-guards 的 VALID_QUESTION_TYPES，
// 过滤掉 inline 编辑器不支持的类型（multiple_choice / composite 需要复杂 UI）
const INLINE_QUESTION_TYPES = VALID_QUESTION_TYPES.filter(
  (t): t is "single_choice" | "text" | "judgment" =>
    t === "single_choice" || t === "text" || t === "judgment",
);
type InlineQuestionType = (typeof INLINE_QUESTION_TYPES)[number];

function isInlineQuestionType(v: string): v is InlineQuestionType {
  return (INLINE_QUESTION_TYPES as readonly string[]).includes(v);
}

export function InlineQuestionEditor({ onAdd, onClose, textbookId, chapterId }: Props) {
  const t = useTranslations("lessonPreparation");
  const [type, setType] = useState<InlineQuestionType>("single_choice");
  const [difficulty, setDifficulty] = useState(3);
  const [text, setText] = useState("");
  const [options, setOptions] = useState<string[]>(["", ""]);
  const [correctIdx, setCorrectIdx] = useState(0);
  const [kpIds, setKpIds] = useState<string[]>([]);
  const [showKpPicker, setShowKpPicker] = useState(false);

  function handleAdd() {
    if (!text.trim()) {
      toast.error(t("questionBank.stemRequired"));
      return;
    }
    const content: Record<string, unknown> =
      type === "single_choice"
        ? {
            text,
            options: options.map((o, i) => ({
              id: String(i),
              text: o,
              isCorrect: i === correctIdx,
            })),
          }
        : type === "judgment"
          ? { text, correctAnswer: correctIdx === 0 }
          : { text };
    const inlineContent: InlineQuestionContent = {
      content,
      type,
      difficulty,
      knowledgePointIds: kpIds,
    };
    const item: ExerciseItem = {
      questionId: `inline_draft_${createId()}`,
      source: "inline",
      score: 5,
      order: 0,
      inlineContent,
    };
    onAdd(item);
  }

  return (
    <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/30">
      <div
        className="bg-surface rounded-lg shadow-xl w-[600px] max-h-[80vh] flex flex-col"
        role="dialog"
        aria-modal="true"
        aria-label={t("questionBank.inlineTitle")}
      >
        {/* P1 修复：包裹 FocusTrap 实现焦点陷阱，支持键盘 Tab 循环与关闭后焦点恢复。
            className="contents" 使 FocusTrap 容器不生成盒子，子元素直接参与父级 flex 布局。 */}
        <FocusTrap className="contents">
          <div className="flex justify-between items-center p-4 border-b">
            <h3 className="font-title-md">{t("questionBank.inlineTitle")}</h3>
            <button onClick={onClose} aria-label={t("action.close")}>
              <X className="w-4 h-4" aria-hidden="true" />
            </button>
          </div>
          <div className="flex-1 overflow-y-auto p-4 space-y-3">
            <div>
              <label htmlFor="inline-question-type" className="text-sm font-medium">
                {t("questionBank.typeLabel")}
              </label>
              <select
                id="inline-question-type"
                value={type}
                onChange={(e) => {
                  if (isInlineQuestionType(e.target.value)) {
                    setType(e.target.value);
                  }
                }}
                className="w-full border rounded px-2 py-1 mt-1"
              >
                <option value="single_choice">{t("questionBank.type.single_choice")}</option>
                <option value="text">{t("questionBank.type.text")}</option>
                <option value="judgment">{t("questionBank.type.judgment")}</option>
              </select>
            </div>
            <div>
              <label htmlFor="inline-question-stem" className="text-sm font-medium">{t("questionBank.stemLabel")}</label>
              <textarea
                id="inline-question-stem"
                value={text}
                onChange={(e) => setText(e.target.value)}
                className="w-full border rounded px-2 py-1 mt-1 min-h-[80px]"
              />
            </div>
            {type === "single_choice" && (
              <div>
                <label className="text-sm font-medium">
                  {t("questionBank.optionsLabel")}
                </label>
                {options.map((opt, i) => (
                  <div key={i} className="flex items-center gap-2 mt-1">
                    <input
                      type="radio"
                      checked={correctIdx === i}
                      onChange={() => setCorrectIdx(i)}
                      aria-label={t("questionBank.correctAnswer")}
                    />
                    <input
                      value={opt}
                      onChange={(e) =>
                        setOptions(
                          options.map((o, j) =>
                            j === i ? e.target.value : o,
                          ),
                        )
                      }
                      className="flex-1 border rounded px-2 py-1"
                      aria-label={t("questionBank.optionLabel", { index: i + 1 })}
                    />
                    {options.length > 2 && (
                      <button
                        onClick={() =>
                          setOptions(options.filter((_, j) => j !== i))
                        }
                        aria-label={t("action.delete")}
                      >
                        {t("action.delete")}
                      </button>
                    )}
                  </div>
                ))}
                {options.length < 6 && (
                  <button
                    onClick={() => setOptions([...options, ""])}
                    className="text-sm text-primary mt-1"
                  >
                    {t("questionBank.addOption")}
                  </button>
                )}
              </div>
            )}
            {type === "judgment" && (
              <div>
                <label className="text-sm font-medium">{t("questionBank.correctAnswer")}</label>
                <div className="flex gap-3 mt-1">
                  <label className="flex items-center gap-1">
                    <input
                      type="radio"
                      checked={correctIdx === 0}
                      onChange={() => setCorrectIdx(0)}
                    />
                    {t("questionBank.correct")}
                  </label>
                  <label className="flex items-center gap-1">
                    <input
                      type="radio"
                      checked={correctIdx === 1}
                      onChange={() => setCorrectIdx(1)}
                    />
                    {t("questionBank.incorrect")}
                  </label>
                </div>
              </div>
            )}
            <div>
              <label htmlFor="inline-question-difficulty" className="text-sm font-medium">{t("questionBank.difficultyLabel")}</label>
              <select
                id="inline-question-difficulty"
                value={difficulty}
                onChange={(e) => setDifficulty(Number(e.target.value))}
                className="w-full border rounded px-2 py-1 mt-1"
              >
                {[1, 2, 3, 4, 5].map((d) => (
                  <option key={d} value={d}>
                    {t("questionBank.difficulty", { level: d })}
                  </option>
                ))}
              </select>
            </div>
            <div>
              <label className="text-sm font-medium">{t("questionBank.knowledgePointLabel")}</label>
              <div className="flex items-center gap-2 mt-1">
                {kpIds.length > 0 && (
                  <span className="text-xs text-on-surface-variant">
                    {t("knowledgePoint.selected", { count: kpIds.length })}
                  </span>
                )}
                <button
                  type="button"
                  onClick={() => setShowKpPicker(true)}
                  className="text-xs text-primary hover:underline inline-flex items-center gap-1"
                  aria-label={t("knowledgePoint.select")}
                >
                  <Tag className="w-3 h-3" aria-hidden="true" />
                  {t("knowledgePoint.select")}
                </button>
              </div>
            </div>
          </div>
          <div className="p-4 border-t flex justify-end gap-2">
            <Button variant="outline" onClick={onClose}>
              {t("action.cancel")}
            </Button>
            <Button onClick={handleAdd}>{t("questionBank.addBtn")}</Button>
          </div>
        </FocusTrap>
      </div>
      {showKpPicker && (
        <LessonPlanErrorBoundary>
          <KnowledgePointPicker
            textbookId={textbookId}
            chapterId={chapterId}
            selectedIds={kpIds}
            onChange={setKpIds}
            onClose={() => setShowKpPicker(false)}
          />
        </LessonPlanErrorBoundary>
      )}
    </div>
  );
}
