"use client";

import { useEffect, useState, useMemo, useCallback } from "react";
import { useSearchParams } from "next/navigation";
import { useTranslations } from "next-intl";
import { useRouter } from "next/navigation";
import { useLessonPlanContextSafe, useLessonPlanTrackerSafe } from "../providers/lesson-plan-provider";
import type { TextbookPickerOption, ChapterPickerOption } from "../providers/lesson-plan-provider";
import { Button } from "@/shared/components/ui/button";
import { cn } from "@/shared/lib/utils";
import { SYSTEM_TEMPLATES } from "../constants";
import { Book, ChevronRight, FileText, Loader2, Search, Clock } from "lucide-react";
import type { LessonPlanTemplate } from "../types";

/** V5-9：localStorage 中最近使用教材的存储键 */
const RECENT_TEXTBOOKS_KEY = "lesson-prep:recent-textbooks";
const MAX_RECENT = 5;

/** 读取最近使用教材 ID 列表 */
function readRecentTextbookIds(): string[] {
  if (typeof window === "undefined") return [];
  try {
    const raw = window.localStorage.getItem(RECENT_TEXTBOOKS_KEY);
    if (!raw) return [];
    const arr = JSON.parse(raw);
    if (!Array.isArray(arr)) return [];
    return arr.filter((x): x is string => typeof x === "string").slice(0, MAX_RECENT);
  } catch {
    return [];
  }
}

/** 写入最近使用教材 ID 列表（新选择放在最前，去重，最多 MAX_RECENT 条） */
function writeRecentTextbookId(id: string): void {
  if (typeof window === "undefined") return;
  try {
    const prev = readRecentTextbookIds();
    const next = [id, ...prev.filter((x) => x !== id)].slice(0, MAX_RECENT);
    window.localStorage.setItem(RECENT_TEXTBOOKS_KEY, JSON.stringify(next));
  } catch {
    // localStorage 不可用时静默失败
  }
}

export function TemplatePicker() {
  const t = useTranslations("lessonPreparation");
  const router = useRouter();
  const ctx = useLessonPlanContextSafe();
  const service = ctx?.service ?? null;
  const tracker = useLessonPlanTrackerSafe();
  const searchParams = useSearchParams();

  const [textbooks, setTextbooks] = useState<TextbookPickerOption[]>([]);
  const [textbookId, setTextbookId] = useState<string>("");
  const [chapters, setChapters] = useState<ChapterPickerOption[]>([]);
  const [chapterId, setChapterId] = useState<string>(
    () => searchParams.get("chapterId") ?? "",
  );
  const [loadedTextbookId, setLoadedTextbookId] = useState<string | null>(null);
  const [selected, setSelected] = useState<string>("");
  const [title, setTitle] = useState("");
  const [error, setError] = useState<string | null>(null);
  const [loadingTextbooks, setLoadingTextbooks] = useState(true);
  // P1-6：个人模板
  const [personalTemplates, setPersonalTemplates] = useState<LessonPlanTemplate[]>([]);
  // V5-9：教材搜索 + 最近使用
  const [searchQuery, setSearchQuery] = useState("");
  const [recentIds, setRecentIds] = useState<string[]>([]);

  // V5-9：客户端挂载后读取最近使用教材
  useEffect(() => {
    setRecentIds(readRecentTextbookIds());
  }, []);

  // V5-9：客户端模糊搜索过滤教材（标题/学科/年级/出版社）
  const filteredTextbooks = useMemo(() => {
    if (!searchQuery.trim()) return textbooks;
    const q = searchQuery.trim().toLowerCase();
    return textbooks.filter((tb) => {
      const title = (tb.title ?? "").toLowerCase();
      const subject = (tb.subject ?? "").toLowerCase();
      const grade = (tb.grade ?? "").toLowerCase();
      return title.includes(q) || subject.includes(q) || grade.includes(q);
    });
  }, [textbooks, searchQuery]);

  // V5-9：最近使用的教材（按 recentIds 顺序，且仍存在于 textbooks 列表中）
  const recentTextbooks = useMemo(() => {
    if (recentIds.length === 0) return [];
    return recentIds
      .map((id) => textbooks.find((tb) => tb.id === id))
      .filter((tb): tb is TextbookPickerOption => tb !== undefined);
  }, [recentIds, textbooks]);

  // V5-9：选择教材时记录到 localStorage
  const handleTextbookSelect = useCallback((id: string) => {
    setTextbookId(id);
    setChapterId("");
    if (id) writeRecentTextbookId(id);
    setRecentIds(readRecentTextbookIds());
  }, []);

  // 派生：当前教材的章节是否正在加载
  const loadingChapters = !!textbookId && textbookId !== loadedTextbookId;

  // 初始加载教材列表 + URL 参数预选 + 个人模板（P1-6）
  useEffect(() => {
    if (!service) return;
    let cancelled = false;
    service.getTextbooksForPicker()
      .then((res) => {
        if (cancelled) return;
        if (res.success && res.data) {
          setTextbooks(res.data.textbooks);
          // URL 参数预选
          const urlTextbookId = searchParams.get("textbookId");
          if (urlTextbookId && res.data.textbooks.some((tb) => tb.id === urlTextbookId)) {
            setTextbookId(urlTextbookId);
          }
        }
      })
      .catch((e) => {
        console.error("[TemplatePicker] load textbooks failed", e);
      })
      .finally(() => {
        if (!cancelled) setLoadingTextbooks(false);
      });

    // P1-6：加载个人模板
    service.getLessonPlanTemplates()
      .then((res) => {
        if (cancelled) return;
        if (res.success && res.data) {
          const personal = res.data.templates.filter((tpl) => tpl.type === "personal");
          setPersonalTemplates(personal);
        }
      })
      .catch((e) => {
        console.error("[TemplatePicker] load personal templates failed", e);
      });
    return () => {
      cancelled = true;
    };
  }, [searchParams, service]);

  // 教材变化时加载章节
  useEffect(() => {
    if (!textbookId || !service) {
      return;
    }
    let cancelled = false;
    service.getChaptersForPicker(textbookId)
      .then((res) => {
        if (cancelled) return;
        if (res.success && res.data) {
          setChapters(res.data.chapters);
          setLoadedTextbookId(textbookId);
        }
      })
      .catch((e) => {
        console.error("[TemplatePicker] load chapters failed", e);
      });
    return () => {
      cancelled = true;
    };
  }, [textbookId, service]);

  // 扁平化章节列表（用于下拉选择，带缩进前缀）
  const flattenedChapters = useMemo(() => {
    const result: { id: string; title: string; depth: number }[] = [];
    function walk(list: ChapterPickerOption[], depth: number) {
      for (const ch of list) {
        result.push({ id: ch.id, title: ch.title, depth });
        if (ch.children && Array.isArray(ch.children) && ch.children.length > 0) {
          // P1 修复：ChapterPickerOption.children 已改为递归类型，无需 as 断言
          walk(ch.children, depth + 1);
        }
      }
    }
    walk(chapters, 0);
    return result;
  }, [chapters]);

  // 选中章节时自动填充标题（如果标题为空）
  const selectedChapter = useMemo(
    () => flattenedChapters.find((c) => c.id === chapterId),
    [flattenedChapters, chapterId],
  );

  const handleChapterChange = useCallback((id: string) => {
    setChapterId(id);
    // 如果标题为空，用章节标题预填
    const ch = flattenedChapters.find((c) => c.id === id);
    if (ch && !title) {
      setTitle(ch.title);
    }
  }, [flattenedChapters, title]);

  const selectedTextbook = textbooks.find((tb) => tb.id === textbookId);

  const canSubmit = !!selected && !!title && !!textbookId && !!chapterId;

  async function handleSubmit(formData: FormData) {
    if (!service) return;
    setError(null);
    if (!textbookId || !chapterId) {
      setError(t("picker.errorTextbookChapterRequired"));
      return;
    }
    formData.set("templateId", selected);
    formData.set("title", title);
    formData.set("textbookId", textbookId);
    formData.set("chapterId", chapterId);
    try {
      const res = await service.createLessonPlan(null, formData);
      if (res.success && res.data) {
        tracker.track("lesson_plan.create", { planId: res.data.planId, templateId: selected });
        router.push(`/teacher/lesson-plans/${res.data.planId}/edit`);
      } else {
        setError(res.message ?? t("error.createFailed"));
      }
    } catch (e) {
      console.error("[TemplatePicker] create failed", e);
      setError(t("error.createFailed"));
    }
  }

  return (
    <form action={handleSubmit} className="max-w-3xl mx-auto p-6 space-y-6">
      {/* 步骤 1：选择教材 */}
      <div>
        <label className="font-title-md block mb-2 flex items-center gap-2">
          <Book className="w-4 h-4" />
          {t("picker.textbookLabel")}
          <span className="text-error text-sm">*</span>
        </label>
        {loadingTextbooks ? (
          <div className="flex items-center gap-2 text-on-surface-variant text-sm">
            <Loader2 className="w-4 h-4 animate-spin" />
            {t("picker.loadingTextbooks")}
          </div>
        ) : textbooks.length === 0 ? (
          <p className="text-on-surface-variant text-sm">{t("picker.noTextbooks")}</p>
        ) : (
          <div className="space-y-2">
            {/* V5-9：搜索框 */}
            <div className="relative">
              <Search className="absolute left-2 top-1/2 -translate-y-1/2 w-4 h-4 text-on-surface-variant" aria-hidden="true" />
              <input
                type="search"
                value={searchQuery}
                onChange={(e) => setSearchQuery(e.target.value)}
                placeholder={t("picker.searchTextbookPlaceholder")}
                className="w-full border border-outline-variant rounded-lg pl-8 pr-3 py-2 bg-surface text-sm"
                aria-label={t("picker.searchTextbookLabel")}
              />
            </div>

            {/* V5-9：最近使用教材（无搜索词时显示） */}
            {!searchQuery.trim() && recentTextbooks.length > 0 && (
              <div className="space-y-1">
                <div className="text-xs font-medium text-on-surface-variant flex items-center gap-1">
                  <Clock className="w-3 h-3" aria-hidden="true" />
                  {t("picker.recentSection")}
                </div>
                <div className="flex flex-wrap gap-1">
                  {recentTextbooks.map((tb) => (
                    <button
                      type="button"
                      key={tb.id}
                      onClick={() => handleTextbookSelect(tb.id)}
                      className={cn(
                        "text-xs px-2 py-1 rounded border transition-colors",
                        textbookId === tb.id
                          ? "border-primary bg-primary/10 text-primary"
                          : "border-outline-variant hover:border-primary/50",
                      )}
                    >
                      {tb.title}
                      {tb.grade ? ` · ${tb.grade}` : ""}
                    </button>
                  ))}
                </div>
              </div>
            )}

            {/* 教材下拉框（过滤后） */}
            <select
              value={textbookId}
              onChange={(e) => handleTextbookSelect(e.target.value)}
              required
              className="w-full border border-outline-variant rounded-lg px-3 py-2 bg-surface"
            >
              <option value="">{t("picker.selectTextbook")}</option>
              {filteredTextbooks.map((tb) => (
                <option key={tb.id} value={tb.id}>
                  {tb.title}
                  {tb.subject ? ` · ${tb.subject}` : ""}
                  {tb.grade ? ` · ${tb.grade}` : ""}
                </option>
              ))}
            </select>
            {searchQuery.trim() && filteredTextbooks.length === 0 && (
              <p className="text-xs text-on-surface-variant">
                {t("picker.searchEmpty")}
              </p>
            )}
          </div>
        )}
      </div>

      {/* 步骤 2：选择章节 */}
      <div>
        <label className="font-title-md block mb-2 flex items-center gap-2">
          <FileText className="w-4 h-4" />
          {t("picker.chapterLabel")}
          <span className="text-error text-sm">*</span>
        </label>
        {!textbookId ? (
          <p className="text-on-surface-variant text-sm">{t("picker.selectTextbookFirst")}</p>
        ) : loadingChapters ? (
          <div className="flex items-center gap-2 text-on-surface-variant text-sm">
            <Loader2 className="w-4 h-4 animate-spin" />
            {t("picker.loadingChapters")}
          </div>
        ) : flattenedChapters.length === 0 ? (
          <p className="text-on-surface-variant text-sm">{t("picker.noChapters")}</p>
        ) : (
          <select
            value={chapterId}
            onChange={(e) => handleChapterChange(e.target.value)}
            required
            className="w-full border border-outline-variant rounded-lg px-3 py-2 bg-surface"
          >
            <option value="">{t("picker.selectChapter")}</option>
            {flattenedChapters.map((ch) => (
              <option key={ch.id} value={ch.id}>
                {"　".repeat(ch.depth)}
                {ch.depth > 0 ? "└ " : ""}
                {ch.title}
              </option>
            ))}
          </select>
        )}
        {selectedChapter && (
          <p className="text-xs text-on-surface-variant mt-1 flex items-center gap-1">
            <ChevronRight className="w-3 h-3" />
            {t("picker.selectedChapter", { chapter: selectedChapter.title })}
          </p>
        )}
      </div>

      {/* 步骤 3：标题 */}
      <div>
        <label className="font-title-md block mb-2">{t("template.titleLabel")}</label>
        <input
          value={title}
          onChange={(e) => setTitle(e.target.value)}
          required
          className="w-full border border-outline-variant rounded-lg px-3 py-2"
          placeholder={t("template.titlePlaceholder")}
        />
      </div>

      {/* 步骤 4：模板 */}
      <div>
        <label className="font-title-md block mb-2">{t("template.selectLabel")}</label>
        {/* 系统模板 */}
        <div className="text-xs font-medium text-on-surface-variant mb-2 mt-1">
          {t("template.systemSection")}
        </div>
        <div className="grid grid-cols-1 md:grid-cols-2 gap-3">
          {SYSTEM_TEMPLATES.map((tpl) => (
            <button
              type="button"
              key={tpl.id}
              onClick={() => setSelected(tpl.id)}
              // V4 P1-7 修复：使用 cn() 替代模板字符串拼接 className
              className={cn(
                "text-left p-4 border-2 rounded-lg transition-colors",
                selected === tpl.id
                  ? "border-primary bg-primary/5"
                  : "border-outline-variant hover:border-primary/50",
              )}
            >
              <div className="font-title-md">{t(`template.names.${tpl.id}`)}</div>
              <div className="text-sm text-on-surface-variant mt-1">
                {tpl.blocks.length === 0
                  ? t("template.blankHint")
                  : t("template.blockCount", { count: tpl.blocks.length })}
              </div>
            </button>
          ))}
        </div>

        {/* 个人模板（P1-6）*/}
        <div className="text-xs font-medium text-on-surface-variant mb-2 mt-4">
          {t("template.personalSection")}
        </div>
        {personalTemplates.length === 0 ? (
          <p className="text-sm text-on-surface-variant italic">
            {t("template.noPersonalTemplates")}
          </p>
        ) : (
          <div className="grid grid-cols-1 md:grid-cols-2 gap-3">
            {personalTemplates.map((tpl) => (
              <button
                type="button"
                key={tpl.id}
                onClick={() => setSelected(tpl.id)}
                // V4 P1-7 修复：使用 cn() 替代模板字符串拼接 className
                className={cn(
                  "text-left p-4 border-2 rounded-lg transition-colors",
                  selected === tpl.id
                    ? "border-primary bg-primary/5"
                    : "border-outline-variant hover:border-primary/50",
                )}
              >
                <div className="font-title-md flex items-center gap-2">
                  <span className="truncate">{tpl.name}</span>
                  <span className="inline-flex items-center px-1.5 py-0.5 rounded text-[10px] font-medium bg-secondary text-secondary-foreground flex-shrink-0">
                    {t("template.personalBadge")}
                  </span>
                </div>
                <div className="text-sm text-on-surface-variant mt-1">
                  {tpl.blocks.length === 0
                    ? t("template.blankHint")
                    : t("template.blockCount", { count: tpl.blocks.length })}
                </div>
              </button>
            ))}
          </div>
        )}
        {selectedTextbook && selectedChapter && (
          <p className="text-xs text-on-surface-variant mt-2">
            {t("picker.skeletonHint")}
          </p>
        )}
      </div>

      {error && <p className="text-error text-sm">{error}</p>}
      <Button type="submit" disabled={!canSubmit}>
        {t("action.create")}
      </Button>
    </form>
  );
}
