"use client";

import { useMemo, useRef } from "react";
import JoditEditor from "jodit-react";
import type { IJodit } from "jodit/esm/types";

interface CKEditorWrapperProps {
  value: string;
  onChange: (value: string) => void;
  uploadEndpoint: string;
  placeholder?: string;
}

export default function CKEditorWrapper({
  value,
  onChange,
  uploadEndpoint,
  placeholder,
}: CKEditorWrapperProps) {
  const editor = useRef(null);

  const config = useMemo(
    () => ({
      placeholder: placeholder || "Start typing...",

      // Editing area size — bump these to show more rows before scrolling.
      height: 350,
      minHeight: 300,

      // Toolbar — mapped from the CKEditor plugin list:
      // - "paragraph" covers Heading / Blockquote / Code (Normal, H1-H6, Quote, Code dropdown)
      // - "brush" covers both font color and font background color
      // - "align" is a grouped dropdown for left/center/right/justify
      buttons: [
        "undo",
        "redo",
        "|",
        "paragraph",
        "|",
        "font",
        "fontsize",
        "brush",
        "|",
        "bold",
        "italic",
        "underline",
        "strikethrough",
        "superscript",
        "subscript",
        "eraser",
        "|",
        "align",
        "ul",
        "ol",
        "outdent",
        "indent",
        "|",
        "link",
        "table",
        "hr",
        "video",
        "image",
        "|",
        "source",
      ],
      // Same set for smaller viewports; Jodit collapses overflow into a "..." menu automatically.
      buttonsXS: [
        "bold",
        "italic",
        "underline",
        "|",
        "ul",
        "ol",
        "|",
        "image",
        "table",
        "link",
        "|",
        "source",
      ],
      toolbarAdaptive: true,

      // Image upload -> your own endpoint, same contract as the CKEditor
      // CustomUploadAdapter: POST FormData with a "file" field, expects
      // { success: boolean, url?: string, message?: string } back.
      uploader: {
        url: uploadEndpoint,
        insertImageAsBase64URI: false,
        imagesExtensions: ["jpg", "jpeg", "png", "gif", "webp", "svg"],
        filesVariableName: () => "file",

        isSuccess: (resp: any) => !!resp?.success,
        getMessage: (resp: any) => resp?.message || "",

        process: (resp: any) => ({
          files: resp?.success && resp?.url ? [resp.url] : [],
          error: resp?.success ? 0 : 1,
          msg: resp?.message || "",
        }),

        defaultHandlerSuccess: function (this: IJodit, data: { files?: string[] }) {
          (data.files || []).forEach((url) => {
            this.s.insertImage(url, null, 250);
          });
        },

        defaultHandlerError: function (this: IJodit, e: Error) {
          this.message?.message?.(e.message || "Image upload failed", "error", 4000);
        },
      },

      // Drag & drop / paste-in images go through the same uploader above.
      enableDragAndDropFileToEditor: true,

      // Keep the license banner branding out of the toolbar (community build).
      showXPathInStatusbar: false,
    }),
    [uploadEndpoint, placeholder]
  );

  return (
    <JoditEditor
      ref={editor}
      value={value}
      config={config as any}
      tabIndex={1}
      onBlur={(newContent) => onChange(newContent)}
      onChange={() => {}}
    />
  );
}