"use client";

import "@/components/admin/text-editor/style.css"

import { EditorContent, useEditor } from "@tiptap/react";
import StarterKit from "@tiptap/starter-kit";
import React, { useEffect } from "react";
import MenuBar from "./menu-bar";
import TextAlign from "@tiptap/extension-text-align";
import Highlight from "@tiptap/extension-highlight";
import { Table } from '@tiptap/extension-table'
import TableCell from '@tiptap/extension-table-cell'
import TableHeader from '@tiptap/extension-table-header'
import TableRow from '@tiptap/extension-table-row'
import Image from '@tiptap/extension-image'
import Youtube from '@tiptap/extension-youtube'
import Link from '@tiptap/extension-link'

interface RichTextEditorProps {
  content: string;
  onChange: (content: string) => void;
  placeholder?: string;
  isRTL?: boolean;
}

export default function RichTextEditor({
  content,
  onChange,
  isRTL = false,
}: RichTextEditorProps) {
  const editor = useEditor({
    extensions: [
      StarterKit.configure({
        bulletList: {
          HTMLAttributes: {
            class: "list-disc ml-3",
          },
        },
        orderedList: {
          HTMLAttributes: {
            class: "list-decimal ml-3",
          },
        },
        code: {
          HTMLAttributes: {
            class: "bg-surface-alt px-1.5 py-0.5 rounded text-sm font-mono",
          },
        },
        codeBlock: {
          HTMLAttributes: {
            class: "bg-surface-alt p-3 rounded-lg text-sm font-mono overflow-x-auto",
          },
        },
      }),
      Table.configure({
        HTMLAttributes: {
          class: "w-full border-collapse border border-border",
        },
        resizable: true,
      }),
      TableRow,
      TableHeader.configure({
        HTMLAttributes: {
          class: "border border-border bg-surface-alt text-left p-2 font-semibold",
        },
      }),
      TableCell.configure({
        HTMLAttributes: {
          class: "border border-border p-2",
        },
      }),      
      TextAlign.configure({
        types: ["heading", "paragraph"],
      }),
      Highlight.configure({
        HTMLAttributes: {
          class: "bg-warning-light text-warning",
        },
      }),
      Image.configure({
        inline: true,
        allowBase64: true,
        HTMLAttributes: {
          class: "max-w-full h-auto rounded-lg",
        },
      }),      
      Youtube.configure({
        controls: true,
        nocookie: true,
        allowFullscreen: false,
        origin: 'youtube.com',
        HTMLAttributes: {
          class: "w-full aspect-video rounded-lg",
        },
      }),
      Link.configure({
        HTMLAttributes: {
          class: "text-info underline cursor-pointer hover:opacity-80",
          rel: 'noopener noreferrer',
        },
        openOnClick: true,
        autolink: true,
        defaultProtocol: 'https',
        protocols: ['http', 'https'],
      }),      
    ],
    content: content,
    editorProps: {
      attributes: {
        class: "min-h-[300px] rounded-lg py-3 px-4 prose prose-sm max-w-none focus:outline-none",
        style: `
          background: var(--color-surface);
          color: var(--color-text);
          border: 1px solid var(--color-border);
        `,
        dir: isRTL ? 'rtl' : 'ltr',
      },
    },
    immediatelyRender: false,
    onUpdate: ({ editor }) => {
      onChange(editor.getHTML());
    },
  });

  // Update editor content when the "content" prop changes
  useEffect(() => {
    if (editor && content !== editor.getHTML()) {
      editor.commands.setContent(content, { emitUpdate: false })
    }
  }, [content, editor]);

  // Update dir when isRTL prop changes (e.g. switching language tabs)
  useEffect(() => {
    if (!editor) return;
    const el = editor.view.dom as HTMLElement;
    el.setAttribute('dir', isRTL ? 'rtl' : 'ltr');
  }, [isRTL, editor]);

  return (
    <div className="rich-text-editor-wrapper">
      <MenuBar editor={editor} />
      <EditorContent editor={editor} />
    </div>
  );
}