"use client";

import { useEditor, EditorContent } from "@tiptap/react";
import StarterKit from "@tiptap/starter-kit";
import Link from "@tiptap/extension-link";
import Underline from "@tiptap/extension-underline";
import TextAlign from "@tiptap/extension-text-align";
import Placeholder from "@tiptap/extension-placeholder";
import HorizontalRule from "@tiptap/extension-horizontal-rule";
import { useEffect, useImperativeHandle, forwardRef } from "react";
import {
  AlignCenter,
  AlignLeft,
  AlignRight,
  Bold,
  Heading2,
  Italic,
  Link2,
  List,
  ListOrdered,
  Minus,
  Underline as UnderlineIcon,
} from "lucide-react";
import { cn } from "@/lib/utils";
import { Button } from "@/components/ui/button";

export type RichTextEditorHandle = {
  insertVariable: (token: string) => void;
  getHtml: () => string;
  setHtml: (html: string) => void;
  focus: () => void;
};

export const RichTextEditor = forwardRef<
  RichTextEditorHandle,
  {
    content: string;
    onChange: (html: string) => void;
    dir?: "rtl" | "ltr";
    placeholder?: string;
    className?: string;
  }
>(function RichTextEditor({ content, onChange, dir = "rtl", placeholder, className }, ref) {
  const editor = useEditor({
    extensions: [
      StarterKit.configure({ heading: { levels: [2, 3] } }),
      Underline,
      HorizontalRule,
      Link.configure({ openOnClick: false, HTMLAttributes: { rel: "noopener noreferrer" } }),
      TextAlign.configure({ types: ["heading", "paragraph"] }),
      Placeholder.configure({ placeholder: placeholder ?? "اكتب محتوى الرسالة..." }),
    ],
    content,
    immediatelyRender: false,
    editorProps: {
      attributes: {
        dir,
        class: "tiptap min-h-[220px] px-4 py-3 focus:outline-none text-sm leading-relaxed",
      },
    },
    onUpdate: ({ editor: ed }) => {
      onChange(ed.getHTML());
    },
    onBlur: ({ editor: ed }) => {
      onChange(ed.getHTML());
    },
  });

  useEffect(() => {
    if (!editor) return;
    if (editor.getHTML() !== content) {
      editor.commands.setContent(content, { emitUpdate: false });
    }
  }, [content, editor]);

  useEffect(() => {
    if (!editor) return;
    const root = editor.view.dom;
    root.setAttribute("dir", dir);
    root.style.direction = dir;
    root.style.textAlign = dir === "rtl" ? "right" : "left";
  }, [dir, editor]);

  useImperativeHandle(ref, () => ({
    insertVariable(token: string) {
      if (!editor) return;
      const insert = token.startsWith("{{") ? token : `{{${token}}}`;
      editor.chain().focus().insertContent(insert).run();
    },
    getHtml() {
      return editor?.getHTML() ?? "";
    },
    setHtml(html: string) {
      editor?.commands.setContent(html, { emitUpdate: true });
    },
    focus() {
      editor?.commands.focus();
    },
  }));

  if (!editor) {
    return (
      <div className="min-h-[220px] animate-pulse rounded-xl border border-border bg-muted/30" />
    );
  }

  const ToolBtn = ({
    onClick,
    active,
    children,
    title,
  }: {
    onClick: () => void;
    active?: boolean;
    children: React.ReactNode;
    title: string;
  }) => (
    <Button
      type="button"
      variant="ghost"
      size="icon"
      title={title}
      className={cn("h-8 w-8 shrink-0", active && "bg-primary/15 text-primary")}
      onClick={onClick}
    >
      {children}
    </Button>
  );

  return (
    <div className={cn("overflow-hidden rounded-xl border border-border bg-card", className)}>
      <div className="flex flex-wrap gap-0.5 border-b border-border bg-muted/40 p-1.5">
        <ToolBtn
          title="Bold"
          active={editor.isActive("bold")}
          onClick={() => editor.chain().focus().toggleBold().run()}
        >
          <Bold className="h-4 w-4" />
        </ToolBtn>
        <ToolBtn
          title="Italic"
          active={editor.isActive("italic")}
          onClick={() => editor.chain().focus().toggleItalic().run()}
        >
          <Italic className="h-4 w-4" />
        </ToolBtn>
        <ToolBtn
          title="Underline"
          active={editor.isActive("underline")}
          onClick={() => editor.chain().focus().toggleUnderline().run()}
        >
          <UnderlineIcon className="h-4 w-4" />
        </ToolBtn>
        <ToolBtn
          title="H2"
          active={editor.isActive("heading", { level: 2 })}
          onClick={() => editor.chain().focus().toggleHeading({ level: 2 }).run()}
        >
          <Heading2 className="h-4 w-4" />
        </ToolBtn>
        <ToolBtn
          title="Bullet list"
          active={editor.isActive("bulletList")}
          onClick={() => editor.chain().focus().toggleBulletList().run()}
        >
          <List className="h-4 w-4" />
        </ToolBtn>
        <ToolBtn
          title="Numbered list"
          active={editor.isActive("orderedList")}
          onClick={() => editor.chain().focus().toggleOrderedList().run()}
        >
          <ListOrdered className="h-4 w-4" />
        </ToolBtn>
        <ToolBtn
          title="Link"
          active={editor.isActive("link")}
          onClick={() => {
            const url = window.prompt("URL");
            if (url) editor.chain().focus().setLink({ href: url }).run();
          }}
        >
          <Link2 className="h-4 w-4" />
        </ToolBtn>
        <ToolBtn
          title="Divider"
          onClick={() => editor.chain().focus().setHorizontalRule().run()}
        >
          <Minus className="h-4 w-4" />
        </ToolBtn>
        <ToolBtn
          title="Align start"
          onClick={() => editor.chain().focus().setTextAlign(dir === "rtl" ? "right" : "left").run()}
        >
          {dir === "rtl" ? <AlignRight className="h-4 w-4" /> : <AlignLeft className="h-4 w-4" />}
        </ToolBtn>
        <ToolBtn
          title="Align center"
          onClick={() => editor.chain().focus().setTextAlign("center").run()}
        >
          <AlignCenter className="h-4 w-4" />
        </ToolBtn>
      </div>
      <EditorContent editor={editor} />
    </div>
  );
});
