'use client';

import React, { useCallback, useRef, useState } from 'react';
import { useEditor, EditorContent } from '@tiptap/react';
import StarterKit from '@tiptap/starter-kit';
import Image from '@tiptap/extension-image';
import Link from '@tiptap/extension-link';
import Placeholder from '@tiptap/extension-placeholder';

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

const MenuButton = ({ onClick, active, children, title }: any) => (
  <button type="button" onMouseDown={e => { e.preventDefault(); onClick(); }}
    className={`w-8 h-8 flex items-center justify-center rounded text-sm transition ${active ? 'bg-gold text-white' : 'text-gray-600 hover:bg-gray-200'}`}
    title={title}>{children}</button>
);

export default function RichTextEditor({ value, onChange, placeholder = 'Tulis konten...' }: RichTextEditorProps) {
  const [showUrlInput, setShowUrlInput] = useState<'link' | 'image' | null>(null);
  const [urlValue, setUrlValue] = useState('');
  const urlInputRef = useRef<HTMLInputElement>(null);
  const fileInputRef = useRef<HTMLInputElement>(null);

  const editor = useEditor({
    extensions: [
      StarterKit,
      Image.configure({ inline: false, allowBase64: true }),
      Link.configure({ openOnClick: false }),
      Placeholder.configure({ placeholder }),
    ],
    content: value,
    onUpdate: ({ editor }) => onChange(editor.getHTML()),
  });

  const addLink = useCallback(() => {
    if (!editor) return;
    if (showUrlInput === 'link' && urlValue) {
      editor.chain().focus().extendMarkRange('link').setLink({ href: urlValue }).run();
      setShowUrlInput(null); setUrlValue('');
    } else {
      const previousUrl = editor.getAttributes('link').href || '';
      setUrlValue(previousUrl);
      setShowUrlInput('link');
      setTimeout(() => urlInputRef.current?.focus(), 100);
    }
  }, [editor, showUrlInput, urlValue]);

  const addImage = useCallback(() => {
    if (!editor) return;
    if (showUrlInput === 'image' && urlValue) {
      editor.chain().focus().setImage({ src: urlValue }).run();
      setShowUrlInput(null); setUrlValue('');
    } else {
      setUrlValue('');
      setShowUrlInput('image');
      setTimeout(() => urlInputRef.current?.focus(), 100);
    }
  }, [editor, showUrlInput, urlValue]);

  const handlePaste = useCallback((e: React.ClipboardEvent) => {
    const items = e.clipboardData?.items;
    if (items) {
      for (const item of Array.from(items)) {
        if (item.type.startsWith('image/')) {
          e.preventDefault();
          const file = item.getAsFile();
          if (file) {
            const reader = new FileReader();
            reader.onload = (ev) => {
              editor?.chain().focus().setImage({ src: ev.target?.result as string }).run();
            };
            reader.readAsDataURL(file);
          }
          return;
        }
      }
    }
  }, [editor]);

  if (!editor) return <div className="border border-gray-200 rounded-lg p-4 text-gray-400">Memuat editor...</div>;

  return (
    <div className="border border-gray-200 rounded-lg overflow-hidden bg-white" onPaste={handlePaste}>
      {/* Toolbar */}
      <div className="flex flex-wrap items-center gap-0.5 px-2 py-1.5 bg-gray-50 border-b border-gray-200">
        <MenuButton onClick={() => editor.chain().focus().toggleBold().run()} active={editor.isActive('bold')} title="Bold"><strong>B</strong></MenuButton>
        <MenuButton onClick={() => editor.chain().focus().toggleItalic().run()} active={editor.isActive('italic')} title="Italic"><em>I</em></MenuButton>
        <MenuButton onClick={() => editor.chain().focus().toggleUnderline().run()} active={editor.isActive('underline')} title="Underline"><u>U</u></MenuButton>
        <MenuButton onClick={() => editor.chain().focus().toggleStrike().run()} active={editor.isActive('strike')} title="Strikethrough"><s>S</s></MenuButton>
        <span className="w-px h-6 bg-gray-300 mx-1" />
        <MenuButton onClick={() => editor.chain().focus().toggleHeading({ level: 2 }).run()} active={editor.isActive('heading', { level: 2 })} title="Heading">H</MenuButton>
        <MenuButton onClick={() => editor.chain().focus().setParagraph().run()} active={editor.isActive('paragraph')} title="Paragraph">¶</MenuButton>
        <span className="w-px h-6 bg-gray-300 mx-1" />
        <MenuButton onClick={() => editor.chain().focus().toggleBulletList().run()} active={editor.isActive('bulletList')} title="Bullet list">•</MenuButton>
        <MenuButton onClick={() => editor.chain().focus().toggleOrderedList().run()} active={editor.isActive('orderedList')} title="Numbered list">1.</MenuButton>
        <MenuButton onClick={() => editor.chain().focus().toggleBlockquote().run()} active={editor.isActive('blockquote')} title="Quote">"</MenuButton>
        <span className="w-px h-6 bg-gray-300 mx-1" />
        <MenuButton onClick={addLink} active={editor.isActive('link')} title="Insert link">🔗</MenuButton>
        <MenuButton onClick={addImage} active={false} title="Insert image via URL">🖼️</MenuButton>
        <label className="w-8 h-8 flex items-center justify-center rounded text-sm cursor-pointer text-gray-600 hover:bg-gray-200 transition" title="Upload image from computer">
          <svg className="w-4 h-4" fill="none" stroke="currentColor" viewBox="0 0 24 24"><path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M4 16l4.586-4.586a2 2 0 012.828 0L16 16m-2-2l1.586-1.586a2 2 0 012.828 0L20 14m-6-6h.01M6 20h12a2 2 0 002-2V6a2 2 0 00-2-2H6a2 2 0 00-2 2v12a2 2 0 002 2z"/></svg>
          <input ref={fileInputRef} type="file" accept="image/*" className="hidden" onChange={e => {
            const file = e.target.files?.[0];
            if (!file) return;
            const reader = new FileReader();
            reader.onload = (ev) => { editor?.chain().focus().setImage({ src: ev.target?.result as string }).run(); };
            reader.readAsDataURL(file);
          }} />
        </label>
        <span className="w-px h-6 bg-gray-300 mx-1" />
        <MenuButton onClick={() => editor.chain().focus().undo().run()} active={false} title="Undo">↩</MenuButton>
        <MenuButton onClick={() => editor.chain().focus().redo().run()} active={false} title="Redo">↪</MenuButton>
      </div>

      {/* URL Input popup */}
      {showUrlInput && (
        <div className="flex gap-2 p-2 bg-gray-50 border-b border-gray-200">
          <input ref={urlInputRef} type="text" value={urlValue} onChange={e => setUrlValue(e.target.value)}
            placeholder={showUrlInput === 'link' ? 'https://...' : 'https://gambar.jpg...'}
            className="flex-1 px-3 py-1.5 text-sm border border-gray-200 rounded-lg focus:outline-none focus:border-gold focus:ring-1 focus:ring-gold/20"
            onKeyDown={e => { if (e.key === 'Enter') { e.preventDefault(); showUrlInput === 'link' ? addLink() : addImage(); } }} />
          <button type="button" onClick={showUrlInput === 'link' ? addLink : addImage}
            className="px-3 py-1.5 text-xs bg-gold text-white rounded-lg hover:bg-gold-dark transition">Insert</button>
          <button type="button" onClick={() => setShowUrlInput(null)}
            className="px-3 py-1.5 text-xs text-gray-500 hover:bg-gray-200 rounded-lg transition">✕</button>
        </div>
      )}

      {/* Editor Content */}
      <EditorContent editor={editor} className="px-4 py-3 text-sm text-gray-700 prose prose-sm max-w-none focus:outline-none min-h-[200px]" />
    </div>
  );
}
