import { useEditor, EditorContent } from '@tiptap/react';
import StarterKit from '@tiptap/starter-kit';
import Underline from '@tiptap/extension-underline';
import Link from '@tiptap/extension-link';
import Image from '@tiptap/extension-image';
import Youtube from '@tiptap/extension-youtube';
import TextAlign from '@tiptap/extension-text-align';
import { useRef, useState } from 'react';
import { api, getErrorMessage } from '@/lib/api';
import {
    BoldIcon,
    ItalicIcon,
    ListBulletIcon,
    NumberedListIcon,
    PhotoIcon,
    LinkIcon,
    VideoCameraIcon,
    ArrowUturnLeftIcon,
    ArrowUturnRightIcon,
    CodeBracketIcon,
    ChatBubbleBottomCenterTextIcon,
    MinusIcon,
    ArrowUpTrayIcon,
    GlobeAltIcon,
    XMarkIcon,
    Bars3BottomLeftIcon,
    Bars3Icon,
    Bars3BottomRightIcon,
} from '@heroicons/react/24/outline';

interface RichEditorProps {
    content: string;
    onChange?: (html: string) => void;
    placeholder?: string;
    editable?: boolean;
    minHeight?: string;
}

export default function RichEditor({
    content,
    onChange,
    editable = true,
    minHeight = '320px',
}: RichEditorProps) {
    const fileInputRef = useRef<HTMLInputElement>(null);
    const [uploading, setUploading] = useState(false);
    const [imageModalOpen, setImageModalOpen] = useState(false);
    const [imageUrlInput, setImageUrlInput] = useState('');
    const [videoModalOpen, setVideoModalOpen] = useState(false);
    const [videoUrlInput, setVideoUrlInput] = useState('');
    const [linkModalOpen, setLinkModalOpen] = useState(false);
    const [linkUrlInput, setLinkUrlInput] = useState('');

    const editor = useEditor({
        extensions: [
            StarterKit.configure({
                heading: {
                    levels: [1, 2, 3],
                },
            }),
            Underline,
            TextAlign.configure({
                types: ['heading', 'paragraph'],
            }),
            Link.configure({
                openOnClick: false,
                HTMLAttributes: {
                    class: 'text-sky-600 underline font-medium hover:text-sky-800',
                    target: '_blank',
                    rel: 'noopener noreferrer',
                },
            }),
            Image.configure({
                allowBase64: true,
                HTMLAttributes: {
                    class: 'rounded-xl max-w-full mx-auto my-4 border border-gray-200 shadow-sm object-cover',
                },
            }),
            Youtube.configure({
                width: 640,
                height: 360,
                HTMLAttributes: {
                    class: 'rounded-xl mx-auto my-4 overflow-hidden shadow-sm aspect-video max-w-full',
                },
            }),
        ],
        content: content || '',
        editable,
        onUpdate: ({ editor }) => {
            if (onChange) {
                onChange(editor.getHTML());
            }
        },
    });

    if (!editor) {
        return <div className="p-4 text-sm text-gray-400">Memuat editor...</div>;
    }

    const handleFileUpload = async (e: React.ChangeEvent<HTMLInputElement>) => {
        const file = e.target.files?.[0];
        if (!file) return;

        // Reset input immediately so same file can be selected again
        e.target.value = '';

        try {
            setUploading(true);
            const formData = new FormData();
            formData.append('file', file);
            formData.append('folder', 'panduan-assets');

            const res = await api.post('/files', formData, {
                headers: { 'Content-Type': 'multipart/form-data' },
            });

            const url = res.data?.url;
            if (url) {
                editor.chain().focus().setImage({ src: url, alt: file.name }).run();
            }
        } catch (err) {
            alert(getErrorMessage(err, 'Gagal mengunggah foto / gambar.'));
        } finally {
            setUploading(false);
            setImageModalOpen(false);
        }
    };

    const handleInsertImageUrl = () => {
        if (!imageUrlInput.trim()) return;
        editor.chain().focus().setImage({ src: imageUrlInput.trim() }).run();
        setImageUrlInput('');
        setImageModalOpen(false);
    };

    const handleInsertVideo = () => {
        if (!videoUrlInput.trim()) return;
        editor.chain().focus().setYoutubeVideo({ src: videoUrlInput.trim() }).run();
        setVideoUrlInput('');
        setVideoModalOpen(false);
    };

    const handleSetLink = () => {
        if (!linkUrlInput.trim()) {
            editor.chain().focus().unsetLink().run();
        } else {
            editor
                .chain()
                .focus()
                .extendMarkRange('link')
                .setLink({ href: linkUrlInput.trim() })
                .run();
        }
        setLinkUrlInput('');
        setLinkModalOpen(false);
    };

    return (
        <div className="border border-gray-300 rounded-xl overflow-hidden bg-white shadow-xs focus-within:border-sky-500 focus-within:ring-2 focus-within:ring-sky-100 transition-all">
            {editable && (
                <div className="bg-gray-50/90 border-b border-gray-200 px-3 py-2 flex flex-wrap items-center gap-1 text-gray-700 select-none">
                    {/* Headings */}
                    <div className="flex items-center space-x-0.5 border-r border-gray-200 pr-2 mr-1">
                        <button
                            type="button"
                            onClick={() => editor.chain().focus().toggleHeading({ level: 1 }).run()}
                            className={`px-2 py-1 text-xs font-bold rounded hover:bg-gray-200 transition ${
                                editor.isActive('heading', { level: 1 }) ? 'bg-sky-100 text-sky-700 font-extrabold' : ''
                            }`}
                            title="Heading 1"
                        >
                            H1
                        </button>
                        <button
                            type="button"
                            onClick={() => editor.chain().focus().toggleHeading({ level: 2 }).run()}
                            className={`px-2 py-1 text-xs font-bold rounded hover:bg-gray-200 transition ${
                                editor.isActive('heading', { level: 2 }) ? 'bg-sky-100 text-sky-700 font-extrabold' : ''
                            }`}
                            title="Heading 2"
                        >
                            H2
                        </button>
                        <button
                            type="button"
                            onClick={() => editor.chain().focus().toggleHeading({ level: 3 }).run()}
                            className={`px-2 py-1 text-xs font-bold rounded hover:bg-gray-200 transition ${
                                editor.isActive('heading', { level: 3 }) ? 'bg-sky-100 text-sky-700 font-extrabold' : ''
                            }`}
                            title="Heading 3"
                        >
                            H3
                        </button>
                        <button
                            type="button"
                            onClick={() => editor.chain().focus().setParagraph().run()}
                            className={`px-2 py-1 text-xs rounded hover:bg-gray-200 transition ${
                                editor.isActive('paragraph') ? 'bg-sky-100 text-sky-700 font-semibold' : ''
                            }`}
                            title="Paragraf Biasa"
                        >
                            P
                        </button>
                    </div>

                    {/* Inline formatting */}
                    <div className="flex items-center space-x-0.5 border-r border-gray-200 pr-2 mr-1">
                        <button
                            type="button"
                            onClick={() => editor.chain().focus().toggleBold().run()}
                            className={`p-1.5 rounded hover:bg-gray-200 transition ${
                                editor.isActive('bold') ? 'bg-sky-100 text-sky-700' : ''
                            }`}
                            title="Tebal (Ctrl+B)"
                        >
                            <BoldIcon className="w-4 h-4" />
                        </button>
                        <button
                            type="button"
                            onClick={() => editor.chain().focus().toggleItalic().run()}
                            className={`p-1.5 rounded hover:bg-gray-200 transition ${
                                editor.isActive('italic') ? 'bg-sky-100 text-sky-700' : ''
                            }`}
                            title="Miring (Ctrl+I)"
                        >
                            <ItalicIcon className="w-4 h-4" />
                        </button>
                        <button
                            type="button"
                            onClick={() => editor.chain().focus().toggleUnderline().run()}
                            className={`p-1.5 rounded hover:bg-gray-200 font-serif underline text-sm transition ${
                                editor.isActive('underline') ? 'bg-sky-100 text-sky-700' : ''
                            }`}
                            title="Garis Bawah (Ctrl+U)"
                        >
                            U
                        </button>
                        <button
                            type="button"
                            onClick={() => editor.chain().focus().toggleStrike().run()}
                            className={`p-1.5 rounded hover:bg-gray-200 line-through text-sm transition ${
                                editor.isActive('strike') ? 'bg-sky-100 text-sky-700' : ''
                            }`}
                            title="Coret"
                        >
                            S
                        </button>
                    </div>

                    {/* Text Alignment */}
                    <div className="flex items-center space-x-0.5 border-r border-gray-200 pr-2 mr-1">
                        <button
                            type="button"
                            onClick={() => editor.chain().focus().setTextAlign('left').run()}
                            className={`p-1.5 rounded hover:bg-gray-200 transition ${
                                editor.isActive({ textAlign: 'left' }) ? 'bg-sky-100 text-sky-700' : ''
                            }`}
                            title="Rata Kiri (Left)"
                        >
                            <Bars3BottomLeftIcon className="w-4 h-4" />
                        </button>
                        <button
                            type="button"
                            onClick={() => editor.chain().focus().setTextAlign('center').run()}
                            className={`p-1.5 rounded hover:bg-gray-200 transition ${
                                editor.isActive({ textAlign: 'center' }) ? 'bg-sky-100 text-sky-700' : ''
                            }`}
                            title="Rata Tengah (Center)"
                        >
                            <Bars3Icon className="w-4 h-4" />
                        </button>
                        <button
                            type="button"
                            onClick={() => editor.chain().focus().setTextAlign('right').run()}
                            className={`p-1.5 rounded hover:bg-gray-200 transition ${
                                editor.isActive({ textAlign: 'right' }) ? 'bg-sky-100 text-sky-700' : ''
                            }`}
                            title="Rata Kanan (Right)"
                        >
                            <Bars3BottomRightIcon className="w-4 h-4" />
                        </button>
                        <button
                            type="button"
                            onClick={() => editor.chain().focus().setTextAlign('justify').run()}
                            className={`p-1.5 rounded hover:bg-gray-200 transition ${
                                editor.isActive({ textAlign: 'justify' }) ? 'bg-sky-100 text-sky-700' : ''
                            }`}
                            title="Rata Kanan Kiri (Justify)"
                        >
                            <svg className="w-4 h-4" viewBox="0 0 24 24" fill="none" stroke="currentColor" strokeWidth="1.5">
                                <path strokeLinecap="round" strokeLinejoin="round" d="M3.75 6.75h16.5M3.75 12h16.5m-16.5 5.25h16.5" />
                            </svg>
                        </button>
                    </div>

                    {/* Lists & Blocks */}
                    <div className="flex items-center space-x-0.5 border-r border-gray-200 pr-2 mr-1">
                        <button
                            type="button"
                            onClick={() => editor.chain().focus().toggleBulletList().run()}
                            className={`p-1.5 rounded hover:bg-gray-200 transition ${
                                editor.isActive('bulletList') ? 'bg-sky-100 text-sky-700' : ''
                            }`}
                            title="Bullet List"
                        >
                            <ListBulletIcon className="w-4 h-4" />
                        </button>
                        <button
                            type="button"
                            onClick={() => editor.chain().focus().toggleOrderedList().run()}
                            className={`p-1.5 rounded hover:bg-gray-200 transition ${
                                editor.isActive('orderedList') ? 'bg-sky-100 text-sky-700' : ''
                            }`}
                            title="Numbered List"
                        >
                            <NumberedListIcon className="w-4 h-4" />
                        </button>
                        <button
                            type="button"
                            onClick={() => editor.chain().focus().toggleBlockquote().run()}
                            className={`p-1.5 rounded hover:bg-gray-200 transition ${
                                editor.isActive('blockquote') ? 'bg-sky-100 text-sky-700' : ''
                            }`}
                            title="Kutipan / Catatan"
                        >
                            <ChatBubbleBottomCenterTextIcon className="w-4 h-4" />
                        </button>
                        <button
                            type="button"
                            onClick={() => editor.chain().focus().toggleCodeBlock().run()}
                            className={`p-1.5 rounded hover:bg-gray-200 transition ${
                                editor.isActive('codeBlock') ? 'bg-sky-100 text-sky-700' : ''
                            }`}
                            title="Blok Kode / Teknis"
                        >
                            <CodeBracketIcon className="w-4 h-4" />
                        </button>
                        <button
                            type="button"
                            onClick={() => editor.chain().focus().setHorizontalRule().run()}
                            className="p-1.5 rounded hover:bg-gray-200 transition"
                            title="Garis Pemisah"
                        >
                            <MinusIcon className="w-4 h-4" />
                        </button>
                    </div>

                    {/* Media & Links */}
                    <div className="flex items-center space-x-0.5 border-r border-gray-200 pr-2 mr-1">
                        <button
                            type="button"
                            onClick={() => {
                                const previousUrl = editor.getAttributes('link').href || '';
                                setLinkUrlInput(previousUrl);
                                setLinkModalOpen(true);
                            }}
                            className={`p-1.5 rounded hover:bg-gray-200 transition ${
                                editor.isActive('link') ? 'bg-sky-100 text-sky-700' : ''
                            }`}
                            title="Sisipkan Link"
                        >
                            <LinkIcon className="w-4 h-4" />
                        </button>

                        <button
                            type="button"
                            onClick={() => setImageModalOpen(true)}
                            className="p-1.5 rounded hover:bg-gray-200 text-sky-600 transition flex items-center gap-1 text-xs font-medium"
                            title="Sisipkan Foto / Ilustrasi Tutorial"
                        >
                            <PhotoIcon className="w-4 h-4" />
                            <span className="hidden sm:inline">Foto</span>
                        </button>

                        <button
                            type="button"
                            onClick={() => setVideoModalOpen(true)}
                            className="p-1.5 rounded hover:bg-gray-200 text-rose-600 transition flex items-center gap-1 text-xs font-medium"
                            title="Embed Video YouTube"
                        >
                            <VideoCameraIcon className="w-4 h-4" />
                            <span className="hidden sm:inline">Video</span>
                        </button>
                    </div>

                    {/* Undo / Redo */}
                    <div className="flex items-center space-x-0.5 ml-auto">
                        <button
                            type="button"
                            onClick={() => editor.chain().focus().undo().run()}
                            disabled={!editor.can().undo()}
                            className="p-1.5 rounded hover:bg-gray-200 disabled:opacity-30 transition"
                            title="Undo"
                        >
                            <ArrowUturnLeftIcon className="w-4 h-4" />
                        </button>
                        <button
                            type="button"
                            onClick={() => editor.chain().focus().redo().run()}
                            disabled={!editor.can().redo()}
                            className="p-1.5 rounded hover:bg-gray-200 disabled:opacity-30 transition"
                            title="Redo"
                        >
                            <ArrowUturnRightIcon className="w-4 h-4" />
                        </button>
                    </div>
                </div>
            )}

            {/* Hidden native file input for image upload */}
            <input
                ref={fileInputRef}
                type="file"
                accept="image/*"
                className="hidden"
                onChange={handleFileUpload}
            />

            {/* Content Area */}
            <div className="p-4 sm:p-5" style={{ minHeight }}>
                <EditorContent
                    editor={editor}
                    className="prose prose-sky max-w-none focus:outline-none min-h-[260px] text-gray-800 text-[15px] leading-[1.5] [&_.tiptap]:focus:outline-none [&_.tiptap]:leading-[1.5] [&_p]:leading-[1.5] [&_li]:leading-[1.5]"
                />
            </div>

            {/* Modal: Insert / Upload Image */}
            {imageModalOpen && (
                <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/40 backdrop-blur-xs p-4">
                    <div className="bg-white rounded-2xl max-w-md w-full p-6 shadow-2xl space-y-4 border border-gray-100">
                        <div className="flex items-center justify-between border-b border-gray-100 pb-3">
                            <div className="flex items-center gap-2 text-sky-600 font-semibold text-base">
                                <PhotoIcon className="w-5 h-5" />
                                <span>Sisipkan Foto / Ilustrasi</span>
                            </div>
                            <button
                                type="button"
                                onClick={() => setImageModalOpen(false)}
                                className="p-1 text-gray-400 hover:text-gray-600 rounded-lg hover:bg-gray-100"
                            >
                                <XMarkIcon className="w-5 h-5" />
                            </button>
                        </div>

                        <div className="space-y-3">
                            <div className="bg-sky-50/70 border border-sky-100 rounded-xl p-4 text-center">
                                <p className="text-xs text-sky-800 mb-3">
                                    Unggah foto langsung dari perangkat Anda (misal: contoh foto angle, posisi kamera, diagram SOP).
                                </p>
                                <button
                                    type="button"
                                    onClick={() => fileInputRef.current?.click()}
                                    disabled={uploading}
                                    className="inline-flex items-center gap-2 px-4 py-2 bg-sky-600 hover:bg-sky-700 text-white rounded-lg text-sm font-medium shadow-xs transition disabled:opacity-50"
                                >
                                    <ArrowUpTrayIcon className="w-4 h-4" />
                                    {uploading ? 'Mengunggah...' : 'Pilih File Gambar'}
                                </button>
                            </div>

                            <div className="relative flex py-1 items-center">
                                <div className="flex-grow border-t border-gray-200"></div>
                                <span className="flex-shrink mx-3 text-xs text-gray-400 uppercase font-medium">atau URL link gambar</span>
                                <div className="flex-grow border-t border-gray-200"></div>
                            </div>

                            <div>
                                <label className="block text-xs font-medium text-gray-600 mb-1">
                                    Alamat URL Gambar
                                </label>
                                <div className="flex gap-2">
                                    <input
                                        type="url"
                                        placeholder="https://example.com/foto-tutorial.jpg"
                                        value={imageUrlInput}
                                        onChange={(e) => setImageUrlInput(e.target.value)}
                                        className="flex-1 text-sm rounded-lg border border-gray-300 px-3 py-2 focus:border-sky-500 focus:outline-none"
                                        onKeyDown={(e) => {
                                            if (e.key === 'Enter') {
                                                e.preventDefault();
                                                handleInsertImageUrl();
                                            }
                                        }}
                                    />
                                    <button
                                        type="button"
                                        onClick={handleInsertImageUrl}
                                        disabled={!imageUrlInput.trim()}
                                        className="px-4 py-2 bg-gray-800 hover:bg-gray-900 text-white rounded-lg text-sm font-medium transition disabled:opacity-40"
                                    >
                                        Pasang
                                    </button>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            )}

            {/* Modal: Insert YouTube Video */}
            {videoModalOpen && (
                <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/40 backdrop-blur-xs p-4">
                    <div className="bg-white rounded-2xl max-w-md w-full p-6 shadow-2xl space-y-4 border border-gray-100">
                        <div className="flex items-center justify-between border-b border-gray-100 pb-3">
                            <div className="flex items-center gap-2 text-rose-600 font-semibold text-base">
                                <VideoCameraIcon className="w-5 h-5" />
                                <span>Embed Video YouTube</span>
                            </div>
                            <button
                                type="button"
                                onClick={() => setVideoModalOpen(false)}
                                className="p-1 text-gray-400 hover:text-gray-600 rounded-lg hover:bg-gray-100"
                            >
                                <XMarkIcon className="w-5 h-5" />
                            </button>
                        </div>

                        <div>
                            <label className="block text-xs font-medium text-gray-600 mb-1">
                                Masukkan Link YouTube (Tutorial / Panduan Video)
                            </label>
                            <input
                                type="url"
                                placeholder="https://www.youtube.com/watch?v=..."
                                value={videoUrlInput}
                                onChange={(e) => setVideoUrlInput(e.target.value)}
                                className="w-full text-sm rounded-lg border border-gray-300 px-3 py-2 focus:border-rose-500 focus:outline-none"
                                onKeyDown={(e) => {
                                    if (e.key === 'Enter') {
                                        e.preventDefault();
                                        handleInsertVideo();
                                    }
                                }}
                            />
                        </div>

                        <div className="flex justify-end gap-2 pt-2">
                            <button
                                type="button"
                                onClick={() => setVideoModalOpen(false)}
                                className="px-3 py-1.5 text-sm text-gray-600 hover:bg-gray-100 rounded-lg"
                            >
                                Batal
                            </button>
                            <button
                                type="button"
                                onClick={handleInsertVideo}
                                disabled={!videoUrlInput.trim()}
                                className="px-4 py-2 bg-rose-600 hover:bg-rose-700 text-white rounded-lg text-sm font-medium transition disabled:opacity-40"
                            >
                                Masukkan Video
                            </button>
                        </div>
                    </div>
                </div>
            )}

            {/* Modal: Insert / Edit Link */}
            {linkModalOpen && (
                <div className="fixed inset-0 z-50 flex items-center justify-center bg-black/40 backdrop-blur-xs p-4">
                    <div className="bg-white rounded-2xl max-w-md w-full p-6 shadow-2xl space-y-4 border border-gray-100">
                        <div className="flex items-center justify-between border-b border-gray-100 pb-3">
                            <div className="flex items-center gap-2 text-sky-600 font-semibold text-base">
                                <GlobeAltIcon className="w-5 h-5" />
                                <span>Sisipkan Tautan (Link)</span>
                            </div>
                            <button
                                type="button"
                                onClick={() => setLinkModalOpen(false)}
                                className="p-1 text-gray-400 hover:text-gray-600 rounded-lg hover:bg-gray-100"
                            >
                                <XMarkIcon className="w-5 h-5" />
                            </button>
                        </div>

                        <div>
                            <label className="block text-xs font-medium text-gray-600 mb-1">
                                URL Tujuan
                            </label>
                            <input
                                type="url"
                                placeholder="https://..."
                                value={linkUrlInput}
                                onChange={(e) => setLinkUrlInput(e.target.value)}
                                className="w-full text-sm rounded-lg border border-gray-300 px-3 py-2 focus:border-sky-500 focus:outline-none"
                                onKeyDown={(e) => {
                                    if (e.key === 'Enter') {
                                        e.preventDefault();
                                        handleSetLink();
                                    }
                                }}
                            />
                        </div>

                        <div className="flex justify-between items-center pt-2">
                            {editor.isActive('link') ? (
                                <button
                                    type="button"
                                    onClick={() => {
                                        editor.chain().focus().unsetLink().run();
                                        setLinkModalOpen(false);
                                    }}
                                    className="text-xs text-red-600 hover:underline"
                                >
                                    Hapus Link
                                </button>
                            ) : <div />}
                            <div className="flex gap-2">
                                <button
                                    type="button"
                                    onClick={() => setLinkModalOpen(false)}
                                    className="px-3 py-1.5 text-sm text-gray-600 hover:bg-gray-100 rounded-lg"
                                >
                                    Batal
                                </button>
                                <button
                                    type="button"
                                    onClick={handleSetLink}
                                    className="px-4 py-2 bg-sky-600 hover:bg-sky-700 text-white rounded-lg text-sm font-medium transition"
                                >
                                    Simpan Link
                                </button>
                            </div>
                        </div>
                    </div>
                </div>
            )}
        </div>
    );
}
