"use client";

import { useEditor, EditorContent, Editor } from "@tiptap/react";
import StarterKit from "@tiptap/starter-kit";
import Link from "@tiptap/extension-link";
import Placeholder from "@tiptap/extension-placeholder";
import { useCallback, useEffect } from "react";

interface RichTextEditorProps {
  value: string;
  onChange: (html: string) => void;
  placeholder?: string;
  className?: string;
  minHeight?: string;
}

interface MenuBarProps {
  editor: Editor | null;
}

function MenuBar({ editor }: MenuBarProps) {
  const setLink = useCallback(() => {
    if (!editor) return;
    const previousUrl = editor.getAttributes("link").href;
    const url = window.prompt("URL", previousUrl);

    if (url === null) return;

    if (url === "") {
      editor.chain().focus().extendMarkRange("link").unsetLink().run();
      return;
    }

    editor.chain().focus().extendMarkRange("link").setLink({ href: url }).run();
  }, [editor]);

  if (!editor) return null;

  return (
    <div className="flex flex-wrap gap-1 border-b border-gray-200 p-2 bg-gray-50 rounded-t-lg">
      <button
        type="button"
        onClick={() => editor.chain().focus().toggleBold().run()}
        disabled={!editor.can().chain().focus().toggleBold().run()}
        className={`px-2 py-1 rounded text-sm font-medium transition-colors ${
          editor.isActive("bold")
            ? "bg-primary-100 text-primary-700"
            : "hover:bg-gray-200 text-gray-700"
        }`}
        title="Bold"
      >
        B
      </button>
      <button
        type="button"
        onClick={() => editor.chain().focus().toggleItalic().run()}
        disabled={!editor.can().chain().focus().toggleItalic().run()}
        className={`px-2 py-1 rounded text-sm italic transition-colors ${
          editor.isActive("italic")
            ? "bg-primary-100 text-primary-700"
            : "hover:bg-gray-200 text-gray-700"
        }`}
        title="Italic"
      >
        I
      </button>
      <button
        type="button"
        onClick={setLink}
        className={`px-2 py-1 rounded text-sm transition-colors ${
          editor.isActive("link")
            ? "bg-primary-100 text-primary-700"
            : "hover:bg-gray-200 text-gray-700"
        }`}
        title="Add Link"
      >
        Link
      </button>
      <div className="w-px bg-gray-300 mx-1" />
      <button
        type="button"
        onClick={() => editor.chain().focus().toggleBulletList().run()}
        className={`px-2 py-1 rounded text-sm transition-colors ${
          editor.isActive("bulletList")
            ? "bg-primary-100 text-primary-700"
            : "hover:bg-gray-200 text-gray-700"
        }`}
        title="Bullet List"
      >
        &bull; List
      </button>
      <button
        type="button"
        onClick={() => editor.chain().focus().toggleOrderedList().run()}
        className={`px-2 py-1 rounded text-sm transition-colors ${
          editor.isActive("orderedList")
            ? "bg-primary-100 text-primary-700"
            : "hover:bg-gray-200 text-gray-700"
        }`}
        title="Numbered List"
      >
        1. List
      </button>
      <button
        type="button"
        onClick={() => editor.chain().focus().toggleBlockquote().run()}
        className={`px-2 py-1 rounded text-sm transition-colors ${
          editor.isActive("blockquote")
            ? "bg-primary-100 text-primary-700"
            : "hover:bg-gray-200 text-gray-700"
        }`}
        title="Quote"
      >
        Quote
      </button>
    </div>
  );
}

export default function RichTextEditor({
  value,
  onChange,
  placeholder = "Write something...",
  className = "",
  minHeight = "200px",
}: RichTextEditorProps) {
  const editor = useEditor({
    extensions: [
      StarterKit,
      Link.configure({
        openOnClick: false,
        HTMLAttributes: {
          class: "text-primary-600 underline",
        },
      }),
      Placeholder.configure({
        placeholder,
      }),
    ],
    content: value,
    onUpdate: ({ editor }) => {
      onChange(editor.getHTML());
    },
    editorProps: {
      attributes: {
        class: `prose prose-sm max-w-none focus:outline-none p-4`,
        style: `min-height: ${minHeight}`,
      },
    },
  });

  // Update editor content when value changes externally (e.g., template selection)
  useEffect(() => {
    if (editor && value !== editor.getHTML()) {
      editor.commands.setContent(value);
    }
  }, [value, editor]);

  return (
    <div
      className={`border border-gray-300 rounded-lg overflow-hidden ${className}`}
    >
      <MenuBar editor={editor} />
      <EditorContent editor={editor} />
    </div>
  );
}
