import React, { useEffect } from "react";
import { useEditor, EditorContent } from "@tiptap/react";
import { StarterKit } from "@tiptap/starter-kit";
import { Underline } from "@tiptap/extension-underline";
import { TextAlign } from "@tiptap/extension-text-align";
import { Highlight } from "@tiptap/extension-highlight";
import { Color } from "@tiptap/extension-color";
import { TextStyle } from "@tiptap/extension-text-style";
import { useTheme } from "@context/ThemeContext";
import {
  Bold,
  Italic,
  Underline as UnderlineIcon,
  AlignLeft,
  AlignCenter,
  AlignRight,
  Highlighter,
  Type,
  Undo,
  Redo,
  List,
  ListOrdered,
} from "lucide-react";

const LyricsRichTextEditor = ({ content, onChange, placeholder }) => {
  const { isDark } = useTheme();

  const editor = useEditor({
    extensions: [
      StarterKit.configure({
        heading: false, // Disable headings for lyrics
      }),
      Underline,
      TextAlign.configure({
        types: ["paragraph"],
      }),
      Highlight.configure({
        multicolor: true,
      }),
      Color,
      TextStyle,
    ],
    content: content || "",
    onUpdate: ({ editor }) => {
      // Get text content only, not HTML
      const text = editor.getText();
      onChange(text);
    },
    editorProps: {
      attributes: {
        class: `prose prose-sm max-w-none focus:outline-none min-h-[400px] px-4 py-3 font-mono leading-relaxed whitespace-pre-wrap ${
          isDark ? "prose-invert" : ""
        }`,
      },
      // Handle paste to preserve plain text formatting
      handlePaste: (view, event) => {
        const text = event.clipboardData?.getData("text/plain");
        if (text) {
          // Insert as plain text, preserving line breaks and spacing
          const { state } = view;
          const { tr } = state;
          tr.insertText(text);
          view.dispatch(tr);
          return true; // Prevent default paste
        }
        return false;
      },
    },
  });

  // Update content when prop changes
  useEffect(() => {
    if (editor && content !== editor.getText()) {
      // Set content as plain text
      editor.commands.setContent(
        content ? `<p>${content.replace(/\n/g, "<br>")}</p>` : "",
      );
    }
  }, [content, editor]);

  if (!editor) {
    return null;
  }

  const ToolbarButton = ({ onClick, active, disabled, children, title }) => (
    <button
      type="button"
      onClick={onClick}
      disabled={disabled}
      title={title}
      className={`p-2 rounded transition-all ${
        active
          ? isDark
            ? "bg-cyan-500/30 text-cyan-400"
            : "bg-cyan-100 text-cyan-700"
          : isDark
            ? "bg-white/10 text-gray-300 hover:bg-white/20"
            : "bg-gray-100 text-gray-700 hover:bg-gray-200"
      } ${disabled ? "opacity-50 cursor-not-allowed" : ""}`}
    >
      {children}
    </button>
  );

  const ColorButton = ({ color, label }) => (
    <button
      type="button"
      onClick={() => editor.chain().focus().setColor(color).run()}
      title={label}
      className={`w-6 h-6 rounded border-2 transition-all hover:scale-110 ${
        editor.isActive("textStyle", { color })
          ? "border-white ring-2 ring-offset-1 ring-cyan-500"
          : isDark
            ? "border-white/20"
            : "border-gray-300"
      }`}
      style={{ backgroundColor: color }}
    />
  );

  return (
    <div
      className={`rounded-lg border overflow-hidden ${
        isDark ? "border-white/10 bg-white/5" : "border-gray-200 bg-white"
      }`}
    >
      {/* Toolbar */}
      <div
        className={`flex flex-wrap items-center gap-1 p-2 border-b ${
          isDark ? "border-white/10 bg-white/5" : "border-gray-200 bg-gray-50"
        }`}
      >
        {/* Text Formatting */}
        <div className="flex items-center gap-1 mr-2">
          <ToolbarButton
            onClick={() => editor.chain().focus().toggleBold().run()}
            active={editor.isActive("bold")}
            title="Bold (Ctrl+B)"
          >
            <Bold size={16} />
          </ToolbarButton>
          <ToolbarButton
            onClick={() => editor.chain().focus().toggleItalic().run()}
            active={editor.isActive("italic")}
            title="Italic (Ctrl+I)"
          >
            <Italic size={16} />
          </ToolbarButton>
          <ToolbarButton
            onClick={() => editor.chain().focus().toggleUnderline().run()}
            active={editor.isActive("underline")}
            title="Underline (Ctrl+U)"
          >
            <UnderlineIcon size={16} />
          </ToolbarButton>
        </div>

        {/* Separator */}
        <div className={`w-px h-6 ${isDark ? "bg-white/20" : "bg-gray-300"}`} />

        {/* Text Alignment */}
        <div className="flex items-center gap-1 mx-2">
          <ToolbarButton
            onClick={() => editor.chain().focus().setTextAlign("left").run()}
            active={editor.isActive({ textAlign: "left" })}
            title="Align Left"
          >
            <AlignLeft size={16} />
          </ToolbarButton>
          <ToolbarButton
            onClick={() => editor.chain().focus().setTextAlign("center").run()}
            active={editor.isActive({ textAlign: "center" })}
            title="Align Center"
          >
            <AlignCenter size={16} />
          </ToolbarButton>
          <ToolbarButton
            onClick={() => editor.chain().focus().setTextAlign("right").run()}
            active={editor.isActive({ textAlign: "right" })}
            title="Align Right"
          >
            <AlignRight size={16} />
          </ToolbarButton>
        </div>

        {/* Separator */}
        <div className={`w-px h-6 ${isDark ? "bg-white/20" : "bg-gray-300"}`} />

        {/* Lists */}
        <div className="flex items-center gap-1 mx-2">
          <ToolbarButton
            onClick={() => editor.chain().focus().toggleBulletList().run()}
            active={editor.isActive("bulletList")}
            title="Bullet List"
          >
            <List size={16} />
          </ToolbarButton>
          <ToolbarButton
            onClick={() => editor.chain().focus().toggleOrderedList().run()}
            active={editor.isActive("orderedList")}
            title="Numbered List"
          >
            <ListOrdered size={16} />
          </ToolbarButton>
        </div>

        {/* Separator */}
        <div className={`w-px h-6 ${isDark ? "bg-white/20" : "bg-gray-300"}`} />

        {/* Highlight */}
        <div className="flex items-center gap-1 mx-2">
          <ToolbarButton
            onClick={() =>
              editor.chain().focus().toggleHighlight({ color: "#fef08a" }).run()
            }
            active={editor.isActive("highlight")}
            title="Highlight"
          >
            <Highlighter size={16} />
          </ToolbarButton>
        </div>

        {/* Separator */}
        <div className={`w-px h-6 ${isDark ? "bg-white/20" : "bg-gray-300"}`} />

        {/* Text Colors */}
        <div className="flex items-center gap-1.5 mx-2">
          <Type
            size={14}
            className={isDark ? "text-gray-400" : "text-gray-500"}
          />
          <ColorButton color="#ef4444" label="Red" />
          <ColorButton color="#f97316" label="Orange" />
          <ColorButton color="#eab308" label="Yellow" />
          <ColorButton color="#22c55e" label="Green" />
          <ColorButton color="#3b82f6" label="Blue" />
          <ColorButton color="#8b5cf6" label="Purple" />
          <ColorButton color="#ec4899" label="Pink" />
          <button
            type="button"
            onClick={() => editor.chain().focus().unsetColor().run()}
            title="Remove Color"
            className={`px-2 py-1 rounded text-xs ${
              isDark
                ? "bg-white/10 text-gray-300 hover:bg-white/20"
                : "bg-gray-100 text-gray-600 hover:bg-gray-200"
            }`}
          >
            Reset
          </button>
        </div>

        {/* Separator */}
        <div className={`w-px h-6 ${isDark ? "bg-white/20" : "bg-gray-300"}`} />

        {/* Undo/Redo */}
        <div className="flex items-center gap-1 mx-2">
          <ToolbarButton
            onClick={() => editor.chain().focus().undo().run()}
            disabled={!editor.can().undo()}
            title="Undo (Ctrl+Z)"
          >
            <Undo size={16} />
          </ToolbarButton>
          <ToolbarButton
            onClick={() => editor.chain().focus().redo().run()}
            disabled={!editor.can().redo()}
            title="Redo (Ctrl+Y)"
          >
            <Redo size={16} />
          </ToolbarButton>
        </div>
      </div>

      {/* Editor Content */}
      <EditorContent
        editor={editor}
        className={`${isDark ? "text-white" : "text-gray-900"}`}
      />

      {/* Footer hint */}
      <div
        className={`px-4 py-2 text-xs border-t ${
          isDark
            ? "border-white/10 bg-white/5 text-gray-500"
            : "border-gray-200 bg-gray-50 text-gray-400"
        }`}
      >
        💡 Use keyboard shortcuts: <strong>Ctrl+B</strong> Bold,{" "}
        <strong>Ctrl+I</strong> Italic, <strong>Ctrl+U</strong> Underline,{" "}
        <strong>Ctrl+Z</strong> Undo | 🎸 Paste lyrics with chords on line above
        - they'll be auto-detected and positioned!
      </div>
    </div>
  );
};

export default LyricsRichTextEditor;
