"use client";

import dynamic from "next/dynamic";
import { useMemo } from "react";
import { QuillEditorSkeleton } from "@/components/shared/skeletons";
import "react-quill-new/dist/quill.snow.css";

const ReactQuill = dynamic(() => import("react-quill-new"), {
  ssr: false,
  loading: () => <QuillEditorSkeleton />,
});

export const DEFAULT_QUILL_MODULES = {
  toolbar: [
    [{ header: [1, 2, 3, false] }],
    [{ size: ["small", false, "large", "huge"] }],
    ["bold", "italic", "underline", "strike"],
    ["blockquote", "code-block"],
    [{ list: "ordered" }, { list: "bullet" }],
    [{ indent: "-1" }, { indent: "+1" }],
    [{ align: [] }],
    ["link"],
    [{ color: [] }, { background: [] }],
    ["clean"],
  ],
} as const;

export const DEFAULT_QUILL_FORMATS = [
  "header",
  "size",
  "bold",
  "italic",
  "underline",
  "strike",
  "blockquote",
  "code-block",
  "list",
  "indent",
  "align",
  "link",
  "color",
  "background",
] as const;

export interface RichTextEditorProps {
  value: string;
  onChange: (value: string) => void;
  placeholder?: string;
  modules?: Record<string, unknown>;
  formats?: string[];
  className?: string;
  /** Optional ref to the wrapper div (for reading .ql-editor innerHTML) */
  editorRef?: React.Ref<HTMLDivElement>;
}

/**
 * Common React Quill wrapper with default toolbar and formats.
 * Use editorRef to read HTML on submit (e.g. quillRef.current?.querySelector(".ql-editor")?.innerHTML).
 */
export function RichTextEditor({
  value,
  onChange,
  placeholder,
  modules = DEFAULT_QUILL_MODULES,
  formats = [...DEFAULT_QUILL_FORMATS],
  className,
  editorRef,
}: RichTextEditorProps) {
  const modulesMemo = useMemo(() => modules, [modules]);
  const formatsMemo = useMemo(() => formats, [formats]);

  return (
    <div ref={editorRef} className={className}>
      <ReactQuill
        theme="snow"
        value={value}
        onChange={onChange}
        placeholder={placeholder}
        modules={modulesMemo}
        formats={formatsMemo}
      />
    </div>
  );
}
