"use client";

import { useEffect, useState } from "react";
import { useTranslations } from "next-intl";
import { Button } from "@/shared/components/ui/button";
import { FocusTrap } from "@/shared/components/a11y/focus-trap";
import { KnowledgePointSkeleton } from "./lesson-plan-skeleton";
import { X } from "lucide-react";
import { useLessonPlanContextSafe } from "../providers/lesson-plan-provider";
import type { KnowledgePointOption } from "../providers/lesson-plan-provider";

interface Props {
  textbookId?: string;
  chapterId?: string;
  selectedIds: string[];
  onChange: (ids: string[]) => void;
  onClose: () => void;
}

export function KnowledgePointPicker({
  textbookId,
  chapterId,
  selectedIds,
  onChange,
  onClose,
}: Props) {
  const t = useTranslations("lessonPreparation");
  const ctx = useLessonPlanContextSafe();
  const service = ctx?.service ?? null;
  const [options, setOptions] = useState<KnowledgePointOption[]>([]);
  const [local, setLocal] = useState<string[]>(selectedIds);
  const [loading, setLoading] = useState(false);
  const [error, setError] = useState<string | null>(null);

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

  useEffect(() => {
    if (!textbookId || !service) return;
    let cancelled = false;
    // V4 P2-3 修复：使用 async IIFE + ignore flag 替代 Promise.resolve().then()
    (async () => {
      setLoading(true);
      setError(null);
      try {
        const res = await service.getKnowledgePointOptions({ textbookId, chapterId });
        if (cancelled) return;
        if (res.success && res.data) {
          setOptions(res.data.options);
        } else {
          setError(res.message ?? t("error.loadFailed"));
        }
      } catch (e) {
        if (cancelled) return;
        console.error("[KnowledgePointPicker] load options failed", e);
        setError(t("error.loadFailed"));
      } finally {
        if (!cancelled) setLoading(false);
      }
    })();
    return () => {
      cancelled = true;
    };
  }, [textbookId, chapterId, t, service]);

  function toggle(id: string) {
    setLocal((prev) =>
      prev.includes(id) ? prev.filter((x) => x !== id) : [...prev, id],
    );
  }

  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("knowledgePoint.title")}
        className="bg-surface rounded-lg shadow-xl w-96 max-h-[70vh] 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">{t("knowledgePoint.title")}</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">
          {loading ? (
            <KnowledgePointSkeleton />
          ) : error ? (
            <p className="text-error text-sm">{error}</p>
          ) : options.length === 0 ? (
            <p className="text-on-surface-variant text-sm">
              {t("knowledgePoint.empty")}
            </p>
          ) : (
            <div className="space-y-1">
              {options.map((kp) => (
                <label
                  key={kp.id}
                  className="flex items-center gap-2 p-2 hover:bg-surface-container-highest rounded cursor-pointer"
                >
                  <input
                    type="checkbox"
                    checked={local.includes(kp.id)}
                    onChange={() => toggle(kp.id)}
                  />
                  <span className="text-sm">{kp.name}</span>
                </label>
              ))}
            </div>
          )}
        </div>
        <div className="p-4 border-t border-outline-variant flex justify-end gap-2">
          <Button variant="outline" size="sm" onClick={onClose}>
            {t("action.cancel")}
          </Button>
          <Button
            size="sm"
            onClick={() => {
              onChange(local);
              onClose();
            }}
          >
            {t("action.confirm")}
          </Button>
        </div>
        </FocusTrap>
      </div>
    </div>
  );
}
