"use client"

import ReactMarkdown from "react-markdown"
import remarkBreaks from "remark-breaks"
import remarkGfm from "remark-gfm"
import rehypeSanitize from "rehype-sanitize"
import { Edit2, Save, Plus, BookOpen } from "lucide-react"
import { useTranslations } from "next-intl"

import type { Chapter } from "../types"
import { cn } from "@/shared/lib/utils"
import { ScrollArea } from "@/shared/components/ui/scroll-area"
import { Button } from "@/shared/components/ui/button"
import { EmptyState } from "@/shared/components/ui/empty-state"
import {
  ContextMenu,
  ContextMenuContent,
  ContextMenuItem,
  ContextMenuTrigger,
} from "@/shared/components/ui/context-menu"
import { RichTextEditor } from "@/shared/components/ui/rich-text-editor"

/**
 * 章节数据组：当前选中章节及其预处理后的内容。
 */
export interface ChapterDataGroup {
  selected: Chapter | null
  processedContent: string
}

/**
 * 编辑状态组：章节内容编辑相关的状态与操作。
 */
export interface EditingStateGroup {
  isEditing: boolean
  editContent: string
  setEditContent: (content: string) => void
  isSaving: boolean
  startEditing: () => void
  cancelEditing: () => void
  saveContent: () => void
}

/**
 * 文本选区组：右键菜单与文本选区相关的状态与操作。
 */
export interface TextSelectionGroup {
  contentRef: React.RefObject<HTMLDivElement | null>
  onPointerDown: (e: React.PointerEvent) => void
  onContextMenuChange: (open: boolean) => void
  selectedText: string
  setCreateDialogOpen: (open: boolean) => void
}

/**
 * 知识点高亮组：高亮跳转相关的状态与操作。
 */
export interface KpHighlightGroup {
  highlightedKpId: string | null
  onHighlight: (id: string) => void
  onSwitchToKnowledgeTab: () => void
}

interface TextbookContentPanelProps {
  chapter: ChapterDataGroup
  editing: EditingStateGroup
  selection: TextSelectionGroup
  highlight: KpHighlightGroup
  canEdit: boolean
}

export function TextbookContentPanel({
  chapter,
  editing,
  selection,
  highlight,
  canEdit,
}: TextbookContentPanelProps): React.ReactNode {
  const t = useTranslations("textbooks")
  const { selected, processedContent } = chapter
  const { isEditing, editContent, setEditContent, isSaving, startEditing, cancelEditing, saveContent } = editing
  const { contentRef, onPointerDown, onContextMenuChange, selectedText, setCreateDialogOpen } = selection
  const { highlightedKpId, onHighlight, onSwitchToKnowledgeTab } = highlight

  if (!selected) {
    return (
      <EmptyState
        icon={BookOpen}
        title={t("reader.selectChapter")}
        description={t("reader.selectChapterDesc")}
        className="h-full border-none shadow-none bg-transparent"
      />
    )
  }

  return (
    <>
      <div className="flex items-center justify-between mb-4 pb-2 border-b px-2 shrink-0">
        <h2 className="text-xl font-bold tracking-tight line-clamp-1">{selected.title}</h2>
        {canEdit && (
          <div className="flex gap-2">
            {isEditing ? (
              <>
                <Button size="sm" variant="ghost" onClick={cancelEditing} disabled={isSaving}>
                  {t("reader.cancel")}
                </Button>
                <Button size="sm" onClick={saveContent} disabled={isSaving}>
                  <Save className="mr-2 h-4 w-4" />
                  {isSaving ? t("reader.saving") : t("reader.save")}
                </Button>
              </>
            ) : (
              <Button size="sm" variant="outline" onClick={startEditing}>
                <Edit2 className="mr-2 h-4 w-4" />
                {t("reader.editContent")}
              </Button>
            )}
          </div>
        )}
      </div>
      <ScrollArea className="flex-1 min-h-0 px-2">
        {isEditing ? (
          <div className="h-full">
            <RichTextEditor
              value={editContent}
              onChange={setEditContent}
              // 任意值 min-h-[500px]：编辑器最小高度，保证可编辑区域可用空间
              className="min-h-[500px] border-none shadow-none"
            />
          </div>
        ) : (
          <ContextMenu onOpenChange={onContextMenuChange}>
            <ContextMenuTrigger asChild>
              <div
                className="p-4 min-h-full"
                ref={contentRef}
                onPointerDown={onPointerDown}
              >
                {selected.content ? (
                  <div className="prose prose-sm dark:prose-invert max-w-none">
                    <ReactMarkdown
                      remarkPlugins={[remarkGfm, remarkBreaks]}
                      rehypePlugins={[rehypeSanitize]}
                      components={{
                        a: ({ href, children, ...props }) => {
                          if (href?.startsWith("#kp-")) {
                            const id = href.replace("#kp-", "")
                            const isHighlighted = highlightedKpId === id
                            return (
                              <span
                                data-kp-id={id}
                                role="button"
                                tabIndex={0}
                                aria-label={t("reader.clickToViewKp")}
                                aria-pressed={isHighlighted}
                                className={cn(
                                  "font-medium text-primary cursor-pointer hover:underline decoration-dashed underline-offset-4 transition-all duration-300",
                                  isHighlighted && "bg-yellow-300 dark:bg-yellow-600 text-black dark:text-white rounded px-1 py-0.5 shadow-sm scale-110 inline-block mx-0.5 font-bold ring-2 ring-yellow-400/50 dark:ring-yellow-500/50"
                                )}
                                onClick={(e) => {
                                  e.preventDefault()
                                  onHighlight(id)
                                  onSwitchToKnowledgeTab()
                                }}
                                onKeyDown={(e) => {
                                  if (e.key === "Enter" || e.key === " ") {
                                    e.preventDefault()
                                    onHighlight(id)
                                    onSwitchToKnowledgeTab()
                                  }
                                }}
                                title={t("reader.clickToViewKp")}
                              >
                                {children}
                              </span>
                            )
                          }
                          return <a href={href} {...props}>{children}</a>
                        }
                      }}
                    >
                      {processedContent}
                    </ReactMarkdown>
                  </div>
                ) : (
                  <EmptyState
                    icon={BookOpen}
                    title={t("reader.emptyContent")}
                    description={t("reader.emptyContentDesc")}
                    className="h-64 border-none shadow-none bg-transparent"
                  />
                )}
              </div>
            </ContextMenuTrigger>
            <ContextMenuContent>
              <ContextMenuItem
                disabled={!selectedText}
                onClick={() => setCreateDialogOpen(true)}
              >
                <Plus className="mr-2 h-4 w-4" />
                {t("reader.addKnowledgePoint")}
              </ContextMenuItem>
            </ContextMenuContent>
          </ContextMenu>
        )}
      </ScrollArea>
    </>
  )
}
