"use client";

import { useCallback, useMemo, useState } from "react";
import dynamic from "next/dynamic";
import type { BooleanPageOptionKey, DocumentStats, PageFont, PageLayoutDensity, PageOptionsState } from "@/types/page-options";
import { cn } from "@/lib/utils";
import { PageOptionsSidebar } from "@/components/editor/page-options-sidebar";
import { useEditorBridgeStore } from "@/store/editor-bridge";
import { ImagePickerProvider } from "@/components/media/image-picker-context";

const BlockNoteEditor = dynamic(
  () => import("@/components/editor/blocknote-editor").then((mod) => mod.BlockNoteEditor),
  { ssr: false },
);

const defaultOptions: PageOptionsState = {
  wideLayout: false,
  smallText: false,
  showHeadingNumbers: true,
  showToc: false,
  showStructure: false,
  protectEditing: false,
  showWordCount: true,
  collapseBacklinks: false,
  pageFont: "default",
  layoutDensity: "normal",
  hideChildPages: false,
  showBlockRefCount: false,
  embedDefaultBlockId: null,
};

const defaultStats: DocumentStats = {
  wordCount: 0,
  characterCount: 0,
  blockCount: 0,
  todoTotal: 0,
  todoDone: 0,
};

export default function PageOptionsPlaygroundPage() {
  const editorBridge = useEditorBridgeStore((s) => s.bridge);
  const [options, setOptions] = useState<PageOptionsState>(defaultOptions);
  const [stats, setStats] = useState<DocumentStats>(defaultStats);
  const documentId = "dev-page-options";
  const workspaceId = "dev-workspace";

  const initialContent = useMemo(
    () => [
      {
        id: "h1",
        type: "heading",
        props: { level: 1 },
        content: [{ type: "text", text: "标题一" }],
      },
      {
        id: "p1",
        type: "paragraph",
        props: {},
        content: [{ type: "text", text: "这是用于回归测试页面选项的示例段落。" }],
      },
    ],
    [],
  );

  const toggleOption = useCallback((key: BooleanPageOptionKey) => {
    setOptions((prev) => ({ ...prev, [key]: !prev[key] }));
  }, []);

  const setPageFont = useCallback((font: PageFont) => setOptions((prev) => ({ ...prev, pageFont: font })), []);
  const setLayoutDensity = useCallback(
    (density: PageLayoutDensity) => setOptions((prev) => ({ ...prev, layoutDensity: density })),
    [],
  );

  const pageRootClass = cn(
    "flex h-[calc(100vh-64px)] overflow-hidden bg-wolai-bg",
    options.pageFont === "song" && "wolai-page-font-song",
    options.pageFont === "kai" && "wolai-page-font-kai",
    options.layoutDensity === "compact" && "wolai-page-density-compact",
    options.layoutDensity === "spacious" && "wolai-page-density-spacious",
    options.smallText && "wolai-small-text",
    options.hideChildPages && "wolai-hide-child-pages",
  );

  return (
    <div className="p-6">
      <div className="mb-4 text-sm text-gray-500">
        Dev Playground：用于 Playwright 回归页面选项（不写入后端）
      </div>
      <ImagePickerProvider documentId={documentId} workspaceId={workspaceId}>
        <div className={pageRootClass}>
          <div className="flex h-full flex-1 flex-col overflow-hidden">
            <div className="border-b border-wolai-border px-12 pb-6 pt-8">
              <div className="text-3xl font-semibold text-wolai-text-primary">页面选项回归测试</div>
              <p className="mt-1 text-sm text-wolai-text-secondary">该页面不会保存任何更改。</p>
            </div>
            <div className="flex-1 overflow-y-auto px-12 py-6">
              <BlockNoteEditor
                documentId={documentId}
                workspaceId={workspaceId}
                initialContent={initialContent as unknown}
                pageOptions={options}
                readOnly={false}
                onStatsChange={setStats}
              />
            </div>
          </div>

          <PageOptionsSidebar
            documentId={documentId}
            options={options}
            stats={stats}
            onToggle={toggleOption}
            onSetPageFont={setPageFont}
            onSetLayoutDensity={setLayoutDensity}
            onSetEmbedDefaultToCursor={() => window.alert("该页面为 Dev Playground，不写入后端")}
            onClearEmbedDefault={() => setOptions((prev) => ({ ...prev, embedDefaultBlockId: null }))}
            onExport={() => window.alert("该页面为 Dev Playground，不提供导出")}
            onOpenHistory={() => window.alert("该页面为 Dev Playground，不提供历史")}
            onOpenComments={() => window.alert("该页面为 Dev Playground，不提供评论")}
            onUndo={() => editorBridge?.undo?.()}
            onRedo={() => editorBridge?.redo?.()}
            onDeletePage={() => window.alert("该页面为 Dev Playground，不提供删除")}
            onOpenMoveEmbedPicker={() => window.alert("该页面为 Dev Playground，不提供移动/嵌入")}
            onCopyPageLink={() => window.alert("该页面为 Dev Playground，不提供复制链接")}
            onCopyPageReference={() => window.alert("该页面为 Dev Playground，不提供引用")}
            onAddToTemplates={() => window.alert("该页面为 Dev Playground，不提供模板")}
          />
        </div>
      </ImagePickerProvider>
    </div>
  );
}
