"use client";

import { useEffect, useRef } from "react";

/**
 * Dependency-free WYSIWYG HTML editor for large/rich admin text (blog content,
 * descriptions). contentEditable + a small toolbar; emits HTML. dir="auto" so
 * Persian and English paragraphs each align correctly.
 */
export function RichTextField({ value, onChange }: { value: string; onChange: (html: string) => void }) {
  const ref = useRef<HTMLDivElement>(null);

  // Seed content once on mount (and when switching records) without fighting the caret.
  useEffect(() => {
    if (ref.current && ref.current.innerHTML !== (value || "")) {
      ref.current.innerHTML = value || "";
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  const emit = () => onChange(ref.current?.innerHTML ?? "");
  const exec = (cmd: string, arg?: string) => {
    ref.current?.focus();
    document.execCommand(cmd, false, arg);
    emit();
  };
  const link = () => {
    const url = prompt("نشانی لینک:");
    if (url) exec("createLink", url);
  };

  const Btn = ({ label, title, cmd, arg }: { label: string; title: string; cmd: string; arg?: string }) => (
    <button
      type="button"
      title={title}
      onMouseDown={(e) => e.preventDefault()}
      onClick={() => exec(cmd, arg)}
      className="rounded px-2 py-1 text-xs text-gray-300 hover:bg-[#1e2235]"
    >
      {label}
    </button>
  );

  return (
    <div className="rounded-lg border border-[#262b40] bg-[#0c0e1a]">
      <div className="flex flex-wrap items-center gap-0.5 border-b border-[#262b40] p-1.5">
        <Btn label="B" title="ضخیم" cmd="bold" />
        <Btn label="I" title="مورب" cmd="italic" />
        <Btn label="U" title="زیرخط" cmd="underline" />
        <span className="mx-1 h-4 w-px bg-[#262b40]" />
        <Btn label="H2" title="عنوان ۲" cmd="formatBlock" arg="<h2>" />
        <Btn label="H3" title="عنوان ۳" cmd="formatBlock" arg="<h3>" />
        <Btn label="¶" title="پاراگراف" cmd="formatBlock" arg="<p>" />
        <span className="mx-1 h-4 w-px bg-[#262b40]" />
        <Btn label="• فهرست" title="فهرست نقطه‌ای" cmd="insertUnorderedList" />
        <Btn label="۱. فهرست" title="فهرست شماره‌دار" cmd="insertOrderedList" />
        <button type="button" title="لینک" onMouseDown={(e) => e.preventDefault()} onClick={link} className="rounded px-2 py-1 text-xs text-gray-300 hover:bg-[#1e2235]">لینک</button>
        <span className="mx-1 h-4 w-px bg-[#262b40]" />
        <Btn label="پاک‌کردن قالب" title="حذف قالب‌بندی" cmd="removeFormat" />
      </div>
      <div
        ref={ref}
        contentEditable
        dir="auto"
        onInput={emit}
        onBlur={emit}
        className="min-h-[260px] max-h-[55vh] overflow-y-auto p-3 text-sm leading-7 text-gray-100 outline-none
                   [&_a]:text-indigo-400 [&_a]:underline
                   [&_h2]:my-2 [&_h2]:text-lg [&_h2]:font-bold [&_h2]:text-white
                   [&_h3]:my-2 [&_h3]:text-base [&_h3]:font-semibold [&_h3]:text-white
                   [&_ul]:my-2 [&_ul]:list-disc [&_ul]:ps-6 [&_ol]:my-2 [&_ol]:list-decimal [&_ol]:ps-6
                   [&_p]:my-1"
      />
    </div>
  );
}
