"use client";

import React, {
  useEffect,
  useRef,
  forwardRef,
  useImperativeHandle,
} from "react";
import Quill from "quill";
import "quill/dist/quill.snow.css";

export type RichTextEditorHandle = {
  getContent: () => string;
};

type Props = {
  value?: string; // ✅ مقدار اولیه
};
const toolbarOptions = [
  ['bold', 'italic', 'underline', 'strike'],        // toggled buttons
  ['blockquote', 'code-block'],
  ['link', 'image', ],

  [{ 'header': 1 }, { 'header': 2 }],               // custom button values
  [{ 'list': 'ordered'}, { 'list': 'bullet' }, { 'list': 'check' }],
  [{ 'indent': '-1'}, { 'indent': '+1' }],          // outdent/indent
  [{ 'direction': 'rtl' }],                         // text direction

  [{ 'size': ['small', false, 'large', 'huge'] }],  // custom dropdown
  [{ 'header': [1, 2, 3, 4, 5, 6, false] }],

  [{ 'color': [] }, { 'background': [] }],          // dropdown with defaults from theme
  [{ 'font': [] }],
  [{ 'align': [] }],

  ['clean']                                         // remove formatting button
];
const RichTextEditor = forwardRef<RichTextEditorHandle, Props>(
  ({ value }, ref) => {
    const editorRef = useRef<HTMLDivElement>(null);
    const quillRef = useRef<Quill | null>(null);

    // init editor
    useEffect(() => {
      if (!editorRef.current || quillRef.current) return;

      quillRef.current = new Quill(editorRef.current, {
        theme: "snow",
        modules: {
          toolbar:toolbarOptions,
        },
        placeholder: "شروع به نوشتن...",
      });

      const editorEl =
        editorRef.current.querySelector<HTMLElement>(".ql-editor");
      if (editorEl) {
        editorEl.setAttribute("dir", "rtl");
        editorEl.style.textAlign = "right";
      }
    }, []);

    // ✅ set content when value changes
    useEffect(() => {
      if (quillRef.current && value !== undefined) {
        quillRef.current.clipboard.dangerouslyPasteHTML(value);
      }
    }, [value]);

    useImperativeHandle(ref, () => ({
      getContent: () => quillRef.current?.root.innerHTML || "",
    }));

    return (
      <div
        ref={editorRef}
        className="w-full"
        style={{ height: "500px", backgroundColor: "white" }}
      />
    );
  },
);

RichTextEditor.displayName = "RichTextEditor";
export default RichTextEditor;
