"use client";

import { Link } from "@tiptap/extension-link";
import { TableKit } from "@tiptap/extension-table";
import { CharacterCount, Placeholder } from "@tiptap/extensions";
import { EditorContent, useEditor, useEditorState, type Editor } from "@tiptap/react";
import { StarterKit } from "@tiptap/starter-kit";
import { useEffect, useRef, useState } from "react";

import { UploadProgressList } from "@/components/media/upload-progress-list";
import { imageFilesFrom } from "@/features/media/upload-client";
import { useImageUpload } from "@/features/media/use-image-upload";
import { trimTrailingEmptyParagraphs } from "@/lib/html";
import { cn } from "@/lib/utils";

import { EditorToolbar } from "./editor-toolbar";
import { FigureImage } from "./extensions/figure-image";
import { insertImages } from "./insert-images";
import { MoveBlock } from "./extensions/move-block";

export function RichTextEditor({
  value,
  onChange,
  invalid,
  onEditorReady,
  toolbarOffset = 0,
}: {
  value: string;
  onChange: (html: string) => void;
  invalid?: boolean;
  onEditorReady?: (editor: Editor) => void;
  /** Height of sticky UI above the toolbar, so it sticks below it. */
  toolbarOffset?: number;
}) {
  const { upload, tasks, clearFinished } = useImageUpload();
  const lastEmitted = useRef(value);
  const onChangeRef = useRef(onChange);
  const uploadRef = useRef(upload);
  const editorRef = useRef<Editor | null>(null);
  const [dragging, setDragging] = useState(false);

  useEffect(() => {
    onChangeRef.current = onChange;
    uploadRef.current = upload;
  });

  const editor = useEditor({
    immediatelyRender: false,
    shouldRerenderOnTransaction: false,
    extensions: [
      StarterKit.configure({
        heading: { levels: [1, 2, 3, 4] },
        link: false,
        dropcursor: { color: "#5b2c9f", width: 2 },
      }),
      // Typing right after a link shouldn't extend it (autolink would otherwise make it inclusive).
      Link.extend({ inclusive: () => false }).configure({
        openOnClick: false,
        autolink: true,
        linkOnPaste: true,
        defaultProtocol: "https",
        protocols: ["mailto", "tel"],
        HTMLAttributes: { rel: null, target: null },
      }),
      Placeholder.configure({
        placeholder: ({ node }) =>
          node.type.name === "heading" ? "Heading" : "Start writing, or paste content and images…",
      }),
      CharacterCount,
      TableKit.configure({ table: { resizable: true, allowTableNodeSelection: true } }),
      FigureImage,
      MoveBlock,
    ],
    content: value,
    editorProps: {
      attributes: {
        class: "cms-prose min-h-[60vh] px-1 py-6 outline-none",
        "aria-label": "Article content",
        role: "textbox",
        "aria-multiline": "true",
      },
      handlePaste: (view, event) => {
        const files = imageFilesFrom(event.clipboardData?.files);
        if (files.length === 0) return false;
        event.preventDefault();
        const position = view.state.selection.from;
        void uploadRef.current(files).then((images) => {
          if (images.length && editorRef.current) insertImages(editorRef.current, images, position);
        });
        return true;
      },
      handleDrop: (view, event, _slice, moved) => {
        if (moved) return false;
        const files = imageFilesFrom(event.dataTransfer?.files);
        if (files.length === 0) return false;
        event.preventDefault();
        const position =
          view.posAtCoords({ left: event.clientX, top: event.clientY })?.pos ??
          view.state.selection.from;
        void uploadRef.current(files).then((images) => {
          if (images.length && editorRef.current) insertImages(editorRef.current, images, position);
        });
        return true;
      },
    },
    onUpdate: ({ editor }) => {
      const html = editor.isEmpty ? "" : trimTrailingEmptyParagraphs(editor.getHTML());
      lastEmitted.current = html;
      onChangeRef.current(html);
    },
  });

  useEffect(() => {
    editorRef.current = editor;
    if (editor) onEditorReady?.(editor);
  }, [editor, onEditorReady]);

  // Content replaced from outside (revision restore, discarding autosave): load it.
  useEffect(() => {
    if (!editor || value === lastEmitted.current) return;
    lastEmitted.current = value;
    editor.commands.setContent(value, { emitUpdate: false });
  }, [editor, value]);

  const counts = useEditorState({
    editor,
    selector: ({ editor }) => ({
      words: editor?.storage.characterCount.words() ?? 0,
      characters: editor?.storage.characterCount.characters() ?? 0,
    }),
  });

  const pendingUploads = tasks.filter((task) => task.status !== "done");

  return (
    <div
      className={cn(
        "relative rounded-xl border bg-card shadow-soft transition-colors",
        invalid && "border-destructive ring-3 ring-destructive/15",
        dragging && "border-primary ring-3 ring-primary/15",
      )}
      onDragOver={(event) => {
        if (Array.from(event.dataTransfer.types).includes("Files")) setDragging(true);
      }}
      onDragLeave={(event) => {
        if (!event.currentTarget.contains(event.relatedTarget as Node | null)) setDragging(false);
      }}
      onDrop={() => setDragging(false)}
    >
      <EditorToolbar
        editor={editor}
        onUpload={async (files) => {
          const position = editor?.state.selection.from;
          const images = await upload(files);
          if (images.length && editor) insertImages(editor, images, position);
        }}
        className="sticky z-20 rounded-t-xl"
        style={{ top: toolbarOffset }}
      />

      {pendingUploads.length > 0 && (
        <div className="border-b bg-muted/40 px-4 py-3">
          <UploadProgressList tasks={pendingUploads} />
          {!pendingUploads.some((task) => task.status === "uploading") && (
            <button
              type="button"
              onClick={clearFinished}
              className="mt-2 text-xs font-medium text-muted-foreground hover:text-foreground"
            >
              Dismiss
            </button>
          )}
        </div>
      )}

      <div className="px-5 sm:px-10 lg:px-14">
        {editor ? (
          <EditorContent editor={editor} />
        ) : (
          <div className="min-h-[60vh] py-6 text-muted-foreground">Loading editor…</div>
        )}
      </div>

      <div className="flex items-center justify-between gap-4 rounded-b-xl border-t bg-muted/30 px-4 py-2 text-xs text-muted-foreground">
        <span className="hidden sm:inline">
          Paste or drop images to upload · <kbd className="font-sans">⌥⇧↑/↓</kbd> moves a block
        </span>
        <span className="tabular-nums">
          {counts?.words.toLocaleString() ?? 0} words · {Math.max(1, Math.round((counts?.words ?? 0) / 225))}{" "}
          min read
        </span>
      </div>
    </div>
  );
}
