"use client";

/**
 * 课案编辑器（核心，P7-insights）
 *
 * 数据来源：
 * - GraphQL LessonPlanDetailQuery
 * - GraphQL UpdateLessonPlanMutation
 * - GraphQL AIGenerateLessonPlanMutation
 *
 * 三栏布局：
 * - 左侧：教材/章节选择 + 班级关联
 * - 中间：富文本编辑器（contenteditable，工具栏：加粗/斜体/标题/列表）
 * - 右侧：AI 助手面板（生成 + 历史记录）
 *
 * 顶部：保存/发布/导出 PDF（window.print()）
 *
 * 维护者：ai13（teacher-portal）
 */

import { useEffect, useRef, useState } from "react";
import { useQuery, useMutation } from "urql";
import { useParams } from "next/navigation";
import Link from "next/link";
import { Loading, Empty } from "@edu/ui-components";
import {
  LessonPlanDetailQuery,
  UpdateLessonPlanMutation,
  AIGenerateLessonPlanMutation,
} from "@/lib/graphql-p7-insights";
import type {
  LessonPlanDetail,
  AIGenerateLessonPlanInput,
  LessonPlanAIHistoryItem,
} from "@/lib/graphql-p7-insights";
import { ClassesQuery } from "@/lib/graphql";
import type { Class } from "@/lib/graphql";

const STATUS_OPTIONS = [
  { value: "DRAFT", label: "草稿" },
  { value: "PUBLISHED", label: "已发布" },
  { value: "ARCHIVED", label: "已归档" },
] as const;

const TEXTBOOKS = [
  { id: "", title: "不关联教材" },
  { id: "tb-001", title: "小学语文三年级上册" },
  { id: "tb-002", title: "小学数学六年级上册" },
  { id: "tb-003", title: "初中英语七年级上册" },
];

export default function LessonPlanEditPage(): JSX.Element {
  const params = useParams<{ planId: string }>();
  const planId = params?.planId ?? "";

  const [result] = useQuery({
    query: LessonPlanDetailQuery,
    variables: { planId },
    pause: !planId,
  });

  const [classesResult] = useQuery({ query: ClassesQuery });
  const classes: Class[] = classesResult.data?.classes ?? [];

  const plan: LessonPlanDetail | undefined = result.data?.lessonPlanDetail;

  const editorRef = useRef<HTMLDivElement | null>(null);
  const [title, setTitle] = useState<string>("");
  const [status, setStatus] = useState<string>("DRAFT");
  const [textbookId, setTextbookId] = useState<string>("");
  const [chapter, setChapter] = useState<string>("");
  const [classIds, setClassIds] = useState<string[]>([]);
  const [saving, setSaving] = useState(false);
  const [saveMsg, setSaveMsg] = useState<string | null>(null);
  const [aiPrompt, setAiPrompt] = useState<string>("");
  const [aiHistory, setAiHistory] = useState<LessonPlanAIHistoryItem[]>([]);
  const [generating, setGenerating] = useState(false);
  const [aiError, setAiError] = useState<string | null>(null);

  const [, updateLessonPlan] = useMutation(UpdateLessonPlanMutation);
  const [, aiGenerate] = useMutation(AIGenerateLessonPlanMutation);

  // 同步初始数据到本地 state + 编辑器内容
  useEffect(() => {
    if (plan) {
      setTitle(plan.title);
      setStatus(plan.status);
      setTextbookId(plan.textbookId ?? "");
      setChapter(plan.chapter);
      setClassIds(plan.classIds);
      setAiHistory(plan.aiHistory);
      if (editorRef.current) {
        editorRef.current.innerText = plan.content;
      }
    }
  }, [plan]);

  const getEditorContent = (): string => {
    if (!editorRef.current) return "";
    // 简化：使用 innerText 作为内容（contenteditable 内的文本）
    return editorRef.current.innerText;
  };

  const setEditorContent = (content: string): void => {
    if (editorRef.current) {
      editorRef.current.innerText = content;
    }
  };

  const appendEditorContent = (content: string): void => {
    if (!editorRef.current) return;
    const current = editorRef.current.innerText;
    editorRef.current.innerText = `${current}\n\n${content}`;
  };

  const exec = (command: string, value?: string): void => {
    if (typeof document !== "undefined" && editorRef.current) {
      editorRef.current.focus();
      document.execCommand(command, false, value);
    }
  };

  const handleSave = async (newStatus?: string): Promise<void> => {
    if (!plan) return;
    setSaving(true);
    setSaveMsg(null);
    const res = await updateLessonPlan({
      input: {
        planId: plan.id,
        title,
        content: getEditorContent(),
        status: (newStatus ?? status) as "DRAFT" | "PUBLISHED" | "ARCHIVED",
        textbookId: textbookId || null,
        chapter,
        classIds,
      },
    });
    setSaving(false);
    if (res.error || !res.data?.updateLessonPlan) {
      setSaveMsg(`保存失败：${res.error?.message ?? "未知错误"}`);
      return;
    }
    if (newStatus) setStatus(newStatus);
    setSaveMsg("已保存 ✓");
    setTimeout(() => setSaveMsg(null), 2000);
  };

  const handleExportPdf = (): void => {
    if (typeof window !== "undefined") window.print();
  };

  const handleAIGenerate = async (): Promise<void> => {
    if (!plan || generating || !aiPrompt) return;
    setGenerating(true);
    setAiError(null);
    const input: AIGenerateLessonPlanInput = {
      subject: plan.subject,
      grade: plan.grade,
      chapter: plan.chapter,
      prompt: aiPrompt,
    };
    const res = await aiGenerate({ input });
    setGenerating(false);
    if (res.error || !res.data?.aiGenerateLessonPlan) {
      setAiError(res.error?.message ?? "生成失败");
      return;
    }
    const generated = res.data.aiGenerateLessonPlan as {
      id: string;
      content: string;
      summary: string;
      model: string;
      generatedAt: string;
    };
    appendEditorContent(generated.content);
    setAiHistory((prev) => [
      {
        id: generated.id,
        prompt: aiPrompt,
        generatedAt: generated.generatedAt,
        model: generated.model,
      },
      ...prev,
    ]);
    setAiPrompt("");
  };

  if (!planId) {
    return (
      <div className="px-10 py-10">
        <Empty title="未指定课案" description="请从课案列表进入编辑" />
      </div>
    );
  }

  if (result.fetching) {
    return (
      <div className="px-10 py-10">
        <Loading lines={6} />
      </div>
    );
  }

  if (result.error) {
    return (
      <div className="px-10 py-10">
        <div className="mark-left mb-4 py-2 border-l-2 border-danger pl-md">
          <p className="text-sm px-3 text-danger">
            加载失败：{result.error.message}
          </p>
        </div>
        <Link
          href="/lesson-plans"
          className="text-tiny uppercase tracking-wide text-accent hover:opacity-70"
        >
          ← 返回课案列表
        </Link>
      </div>
    );
  }

  if (!plan) {
    return (
      <div className="px-10 py-10">
        <Empty title="课案不存在" description="可能已被删除" />
        <Link
          href="/lesson-plans"
          className="mt-4 inline-block text-tiny uppercase tracking-wide text-accent hover:opacity-70"
        >
          ← 返回课案列表
        </Link>
      </div>
    );
  }

  return (
    <div className="px-10 py-10">
      {/* 顶部工具栏 */}
      <header className="mb-6 flex items-baseline justify-between flex-wrap gap-4">
        <div>
          <Link
            href="/lesson-plans"
            className="text-tiny uppercase tracking-wide text-ink-muted hover:opacity-70"
          >
            ← 返回课案列表
          </Link>
          <h1 className="mt-2 text-2xl font-serif text-ink">{plan.title}</h1>
          <p className="mt-1 text-sm text-ink-muted">
            GraphQL LessonPlanDetailQuery · 课案编辑器（P7-insights）
          </p>
        </div>
        <div className="flex items-center gap-3">
          {saveMsg && (
            <span className="text-tiny text-success font-mono">{saveMsg}</span>
          )}
          <button
            type="button"
            onClick={() => handleSave()}
            disabled={saving}
            className="px-4 py-2 text-sm text-ink border border-rule rounded-button hover:bg-subtle disabled:opacity-50"
          >
            {saving ? "保存中…" : "保存"}
          </button>
          <button
            type="button"
            onClick={() => handleSave("PUBLISHED")}
            disabled={saving}
            className="px-4 py-2 text-sm text-ink-on-accent bg-accent rounded-button hover:bg-accent-hover disabled:opacity-50"
          >
            发布
          </button>
          <button
            type="button"
            onClick={handleExportPdf}
            className="px-4 py-2 text-sm text-ink border border-rule rounded-button hover:bg-subtle"
          >
            导出 PDF
          </button>
        </div>
      </header>

      <div className="rule-thin mb-6" />

      {/* 三栏布局 */}
      <div className="grid grid-cols-1 lg:grid-cols-[260px_1fr_320px] gap-6">
        {/* 左侧：教材/章节 + 班级关联 */}
        <aside className="space-y-6">
          <div className="p-5 border border-rule rounded-card bg-surface">
            <h3 className="text-tiny uppercase tracking-wide text-ink-muted mb-3">
              教材与章节
            </h3>
            <label className="block mb-3">
              <span className="text-tiny text-ink-muted">教材</span>
              <select
                value={textbookId}
                onChange={(e) => setTextbookId(e.target.value)}
                className="mt-1 w-full px-2 py-1.5 bg-transparent border-b border-rule text-sm text-ink"
              >
                {TEXTBOOKS.map((t) => (
                  <option key={t.id} value={t.id}>
                    {t.title}
                  </option>
                ))}
              </select>
            </label>
            <label className="block">
              <span className="text-tiny text-ink-muted">章节</span>
              <input
                type="text"
                value={chapter}
                onChange={(e) => setChapter(e.target.value)}
                className="mt-1 w-full px-2 py-1.5 bg-transparent border-b border-rule text-sm text-ink"
              />
            </label>
            <label className="block mt-3">
              <span className="text-tiny text-ink-muted">状态</span>
              <select
                value={status}
                onChange={(e) => setStatus(e.target.value)}
                className="mt-1 w-full px-2 py-1.5 bg-transparent border-b border-rule text-sm text-ink"
              >
                {STATUS_OPTIONS.map((s) => (
                  <option key={s.value} value={s.value}>
                    {s.label}
                  </option>
                ))}
              </select>
            </label>
          </div>

          <div className="p-5 border border-rule rounded-card bg-surface">
            <h3 className="text-tiny uppercase tracking-wide text-ink-muted mb-3">
              班级关联
            </h3>
            {classes.length === 0 ? (
              <p className="text-tiny text-ink-muted">暂无班级</p>
            ) : (
              <ul className="space-y-1.5">
                {classes.map((c) => {
                  const checked = classIds.includes(c.id);
                  return (
                    <li key={c.id}>
                      <label className="flex items-center gap-2 text-sm text-ink">
                        <input
                          type="checkbox"
                          checked={checked}
                          onChange={(e) => {
                            if (e.target.checked) {
                              setClassIds((prev) => [...prev, c.id]);
                            } else {
                              setClassIds((prev) =>
                                prev.filter((id) => id !== c.id),
                              );
                            }
                          }}
                          className="accent-accent"
                        />
                        {c.name}
                      </label>
                    </li>
                  );
                })}
              </ul>
            )}
          </div>
        </aside>

        {/* 中间：富文本编辑器 */}
        <section>
          <div className="mb-3">
            <input
              type="text"
              value={title}
              onChange={(e) => setTitle(e.target.value)}
              className="w-full px-2 py-1.5 bg-transparent border-b border-rule text-xl font-serif text-ink focus:outline-none focus:border-accent"
              placeholder="课案标题"
            />
          </div>
          <div className="mb-3 flex gap-1 border border-rule rounded-button p-1 bg-surface">
            <button
              type="button"
              onClick={() => exec("bold")}
              className="px-3 py-1 text-sm text-ink hover:bg-subtle rounded font-bold"
              title="加粗"
            >
              B
            </button>
            <button
              type="button"
              onClick={() => exec("italic")}
              className="px-3 py-1 text-sm text-ink hover:bg-subtle rounded italic"
              title="斜体"
            >
              I
            </button>
            <button
              type="button"
              onClick={() => exec("formatBlock", "<h2>")}
              className="px-3 py-1 text-sm text-ink hover:bg-subtle rounded font-serif"
              title="标题"
            >
              H
            </button>
            <button
              type="button"
              onClick={() => exec("insertUnorderedList")}
              className="px-3 py-1 text-sm text-ink hover:bg-subtle rounded"
              title="无序列表"
            >
              • 列表
            </button>
            <button
              type="button"
              onClick={() => exec("insertOrderedList")}
              className="px-3 py-1 text-sm text-ink hover:bg-subtle rounded"
              title="有序列表"
            >
              1. 列表
            </button>
            <button
              type="button"
              onClick={() => setEditorContent(getEditorContent())}
              className="px-3 py-1 text-sm text-ink hover:bg-subtle rounded ml-auto"
              title="刷新内容"
            >
              ↻
            </button>
          </div>
          <div
            ref={editorRef}
            contentEditable
            suppressContentEditableWarning
            className="min-h-[480px] p-5 border border-rule rounded-card bg-surface text-sm text-ink font-sans focus:outline-none focus:border-accent whitespace-pre-wrap"
            role="textbox"
            aria-label="课案内容编辑器"
          />
        </section>

        {/* 右侧：AI 助手 */}
        <aside className="space-y-6">
          <div className="p-5 border border-rule rounded-card bg-surface">
            <h3 className="text-tiny uppercase tracking-wide text-ink-muted mb-3">
              AI 助手
            </h3>
            <label className="block mb-3">
              <span className="text-tiny text-ink-muted">生成提示</span>
              <textarea
                value={aiPrompt}
                onChange={(e) => setAiPrompt(e.target.value)}
                rows={4}
                placeholder="如：为本节课生成更详细的练习题与板书设计"
                className="mt-1 w-full px-2 py-1.5 bg-transparent border border-rule rounded text-sm text-ink resize-none focus:outline-none focus:border-accent"
              />
            </label>
            {aiError && (
              <p className="text-tiny text-danger mb-2">{aiError}</p>
            )}
            <button
              type="button"
              onClick={handleAIGenerate}
              disabled={generating || !aiPrompt}
              className="w-full px-3 py-2 text-sm text-ink-on-accent bg-accent rounded-button hover:bg-accent-hover disabled:opacity-50"
            >
              {generating ? "生成中…" : "AI 生成教案"}
            </button>
            <p className="mt-2 text-tiny text-ink-muted">
              生成的内容将追加到编辑器末尾
            </p>
          </div>

          <div className="p-5 border border-rule rounded-card bg-surface">
            <h3 className="text-tiny uppercase tracking-wide text-ink-muted mb-3">
              生成历史
            </h3>
            {aiHistory.length === 0 ? (
              <p className="text-tiny text-ink-muted">暂无生成记录</p>
            ) : (
              <ul className="space-y-3">
                {aiHistory.map((h) => (
                  <li
                    key={h.id}
                    className="pb-3 border-b border-rule last:border-b-0"
                  >
                    <p className="text-sm text-ink">{h.prompt}</p>
                    <p className="mt-1 text-tiny text-ink-muted font-mono">
                      {h.model} · {h.generatedAt.slice(0, 16).replace("T", " ")}
                    </p>
                  </li>
                ))}
              </ul>
            )}
          </div>
        </aside>
      </div>
    </div>
  );
}
