"use client";

import React, { useEffect, useState } from "react";
import { EditorContent, useEditor } from "@tiptap/react";
import RichTextToolbar from "./RichTextToolbar";
import StarterKit from "@tiptap/starter-kit";
import TextAlign from "@tiptap/extension-text-align";
import { TextStyle } from "@tiptap/extension-text-style";
import { Color } from "@tiptap/extension-color";
import { FieldProps } from "formik";

import { useLanguageStore } from "@/store/languageStore";

interface RichTextEditorProps extends FieldProps {
  label: string;
  placeholder?: string;
  /**
   * Forces the editor's writing direction/alignment, overriding the app's
   * current UI language — used when this instance is a dedicated Arabic or
   * English field rather than one that follows the current locale.
   */
  language?: "ar" | "en";
}

const RichTextEditor: React.FC<RichTextEditorProps> = ({
  field,
  form,
  label,
  language,
}) => {
  const { name, value } = field;
  const { setFieldValue, setFieldTouched, errors, touched } = form;
  const uiLanguage = useLanguageStore((s) => s.language);
  const selectedLanguage = language ?? uiLanguage;

  const [isFocused, setIsFocused] = useState(false);

  /*
   * Whether the floating label should sit raised — derived from the form value,
   * not stored.
   *
   * `onUpdate` below writes the editor's HTML straight into the field, so
   * `value` already follows the document; a `hasContent` state written both
   * there and from the sync effect was a second copy of the same fact, and the
   * effect's copy is what `react-hooks/set-state-in-effect` flagged. Tiptap's
   * own empty document serialises as `<p></p>`, which is the case the string
   * comparison covers.
   */
  const hasContent = !!value && value !== "<p></p>";

  const editor = useEditor({
    // Tiptap must not render during SSR or the first client paint mismatches.
    immediatelyRender: false,
    extensions: [
      // Bold, italic, underline, strike, lists and history all ship with
      // StarterKit in Tiptap 3 — registering them again would duplicate names.
      StarterKit.configure({
        bulletList: {
          HTMLAttributes: {
            class: `list-disc ${selectedLanguage === "ar" ? "pr-5" : "pl-5"}`,
          },
        },
        orderedList: {
          HTMLAttributes: {
            class: `list-decimal ${selectedLanguage === "ar" ? "pr-5" : "pl-5"}`,
          },
        },
        heading: false,
        blockquote: false,
        code: false,
        codeBlock: false,
        horizontalRule: false,
        dropcursor: false,
        gapcursor: false,
      }),
      TextAlign.configure({ types: ["paragraph"] }),
      TextStyle,
      Color,
    ],
    editorProps: {
      attributes: {
        dir: selectedLanguage === "ar" ? "rtl" : "ltr",
        // The floating <label> is not tied to the contenteditable; name it here.
        role: "textbox",
        "aria-multiline": "true",
        "aria-label": label,
      },
    },
    content: value || "",
    onUpdate: ({ editor }) => {
      setFieldValue(name, editor.getHTML());
    },
    onFocus: () => setIsFocused(true),
    onBlur: () => {
      setIsFocused(false);
      setFieldTouched(name, true);
    },
  });

  /*
   * Push the field value into the editor when the two differ — a loaded record
   * arriving, a reset, or a programmatic change. Still an effect, correctly so:
   * it writes to an external system (the Tiptap document) and sets no state.
   * The guard keeps it from fighting `onUpdate`, which is the other direction.
   */
  useEffect(() => {
    if (!editor) return;
    if (value !== editor.getHTML()) {
      editor.commands.setContent(value || "");
    }
  }, [editor, value]);

  const errorMessage =
    touched[name] && errors[name] ? String(errors[name]) : null;

  return (
    <div className="mb-4 relative">
      <div className="border rounded-2xl bg-[#29246D]/[0.03]">
        {editor && (
          <RichTextToolbar
            editor={editor}
            selectedLanguage={selectedLanguage}
          />
        )}
        <div>
          <EditorContent
            editor={editor}
            className={`p-3 min-h-[100px] text-primary-5 placeholder:text-primary-5 placeholder:text-lg pt-0 `}
          />
        </div>
      </div>
      <label
        className={`absolute transition-all duration-200 text-primary-5 font-medium start-[15px]
          ${
            isFocused || hasContent
              ? "top-[2px] text-sm px-1"
              : "top-10 text-base"
          }`}
      >
        {label}
      </label>
      {errorMessage && (
        <div className="text-red-500 text-sm mt-1">{errorMessage}</div>
      )}
    </div>
  );
};

export default RichTextEditor;
