'use client';

import { Editor } from '@tiptap/react';
import { useState, useRef, useEffect } from 'react';

interface EditorToolbarProps {
    editor: Editor | null;
}

import { useAuth } from '@/contexts/AuthContext';
import { toast } from 'sonner';

export default function EditorToolbar({ editor }: EditorToolbarProps) {
    const { user } = useAuth();
    const fileInputRef = useRef<HTMLInputElement>(null);
    const [isUploading, setIsUploading] = useState(false);

    const uploadFile = async (file: File) => {
        if (!editor) return;
        setIsUploading(true);
        try {
            const formData = new FormData();
            formData.append('file', file);
            formData.append('folderName', 'blog-images'); // Optional organization

            const token = await user?.getIdToken();
            if (!token) {
                toast.error('로그인이 필요합니다.');
                return;
            }

            const response = await fetch('/api/upload', {
                method: 'POST',
                headers: {
                    'Authorization': `Bearer ${token}`
                },
                body: formData,
            });

            if (!response.ok) throw new Error('Upload failed');

            const data = await response.json();
            const fileId = data.fileId;

            // Insert image using our Proxy API
            // This ensures we can display Drive images without public links
            if (fileId) {
                editor.chain().focus().setImage({ src: `/api/drive-image/${fileId}` }).run();
            }
        } catch (error) {
            console.error('Image upload failed:', error);
            toast.error('이미지 업로드에 실패했습니다.');
        } finally {
            setIsUploading(false);
            if (fileInputRef.current) {
                fileInputRef.current.value = ''; // Reset input
            }
        }
    };

    const handleImageUpload = async (event: React.ChangeEvent<HTMLInputElement>) => {
        const file = event.target.files?.[0];
        if (!file) return;
        await uploadFile(file);
    };

    useEffect(() => {
        if (!editor) return;
        const editorDom = editor.view.dom;

        // PC 전용: 터치 디바이스에서는 리스너 등록 안 함
        const isTouchDevice = 'ontouchstart' in window || navigator.maxTouchPoints > 0;
        if (isTouchDevice) return;

        const setDragStyle = () => {
            editorDom.classList.add('ring-2', 'ring-indigo-400', 'ring-offset-2');
            editorDom.style.background = 'rgba(99, 102, 241, 0.05)';
        };

        const clearDragStyle = () => {
            editorDom.classList.remove('ring-2', 'ring-indigo-400', 'ring-offset-2');
            editorDom.style.background = '';
        };

        const handleDragOver = (e: DragEvent) => {
            e.preventDefault();
            e.stopPropagation();
            setDragStyle();
        };

        const handleDragLeave = (e: DragEvent) => {
            e.preventDefault();
            e.stopPropagation();
            // relatedTarget이 editorDom 내부인지 확인하여 잔류 방지
            if (!editorDom.contains(e.relatedTarget as Node)) {
                clearDragStyle();
            }
        };

        const handleDrop = async (e: DragEvent) => {
            e.preventDefault();
            e.stopPropagation();
            clearDragStyle();

            const files = e.dataTransfer?.files;
            if (!files?.length) return;

            const file = files[0];

            // 클라이언트 검증: image/* 형식만
            if (!file.type.startsWith('image/')) {
                toast.error('이미지 파일만 업로드할 수 있습니다.');
                return;
            }

            // 클라이언트 검증: 10MB 이하
            if (file.size > 10 * 1024 * 1024) {
                toast.error('파일 크기는 10MB 이하만 가능합니다.');
                return;
            }

            await uploadFile(file);
        };

        editorDom.addEventListener('dragover', handleDragOver);
        editorDom.addEventListener('dragleave', handleDragLeave);
        editorDom.addEventListener('drop', handleDrop);

        // 탭 전환 후 복귀 시 dragover 잔류 방지
        const handleVisibilityChange = () => {
            if (document.hidden) clearDragStyle();
        };
        document.addEventListener('visibilitychange', handleVisibilityChange);

        return () => {
            editorDom.removeEventListener('dragover', handleDragOver);
            editorDom.removeEventListener('dragleave', handleDragLeave);
            editorDom.removeEventListener('drop', handleDrop);
            document.removeEventListener('visibilitychange', handleVisibilityChange);
        };
    }, [editor, user]);

    if (!editor) {
        return null;
    }

    const ToolbarButton = ({
        onClick,
        isActive = false,
        disabled = false,
        children,
        title
    }: {
        onClick: () => void,
        isActive?: boolean,
        disabled?: boolean,
        children: React.ReactNode,
        title?: string
    }) => (
        <button
            onClick={(e) => { e.preventDefault(); onClick(); }}
            disabled={disabled}
            title={title}
            className={`
                flex-shrink-0 min-w-[32px] h-8 flex items-center justify-center rounded-lg transition-all font-semibold select-none
                ${isActive
                    ? 'bg-indigo-500 text-white shadow-inner'
                    : 'bg-transparent text-gray-500 hover:bg-gray-100 hover:text-gray-900 border border-transparent'
                }
                ${disabled ? 'opacity-30 cursor-not-allowed' : ''}
            `}
        >
            {children}
        </button>
    );

    return (
        <div className="sticky top-0 z-40 w-full bg-white/95 backdrop-blur-md border-b border-gray-200 mb-4 shadow-sm">
            <div className="flex items-center gap-1 p-2 overflow-x-auto no-scrollbar">
                {/* History */}
                <div className="flex items-center gap-0.5 border-r border-gray-200 pr-2 mr-1">
                    <ToolbarButton
                        onClick={() => editor.chain().focus().undo().run()}
                        disabled={!editor.can().undo()}
                        title="Undo"
                    >
                        <svg className="w-5 h-5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M3 10h10a8 8 0 018 8v2M3 10l6 6m-6-6l6-6" />
                        </svg>
                    </ToolbarButton>
                    <ToolbarButton
                        onClick={() => editor.chain().focus().redo().run()}
                        disabled={!editor.can().redo()}
                        title="Redo"
                    >
                        <svg className="w-5 h-5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M21 10h-10a8 8 0 00-8 8v2M21 10l-6 6m6-6l-6-6" />
                        </svg>
                    </ToolbarButton>
                </div>

                {/* Actions: Tab, Shift+Tab */}
                <ToolbarButton
                    onClick={() => {
                        const { state, view } = editor;
                        const { selection } = state;
                        // 들여쓰기 기능 (목록의 경우 sinkListItem)
                        if (editor.isActive('listItem')) {
                            editor.chain().focus().sinkListItem('listItem').run();
                        } else {
                            editor.chain().focus().insertContent('\t').run();
                        }
                    }}
                    disabled={false}
                    title="Tab (Indent)"
                >
                    <div className="flex items-center gap-0.5 text-sm font-bold opacity-80 px-1">
                        <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2.5} d="M5 12h14M15 5l7 7-7 7" />
                        </svg>
                    </div>
                </ToolbarButton>
                <ToolbarButton
                    onClick={() => {
                        if (editor.isActive('listItem')) {
                            editor.chain().focus().liftListItem('listItem').run();
                        }
                    }}
                    disabled={!editor.can().liftListItem('listItem')}
                    title="Shift+Tab (Outdent)"
                >
                    <div className="flex items-center gap-0.5 text-sm font-bold opacity-80 px-1">
                        <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2.5} d="M19 12H5M9 19l-7-7 7-7" />
                        </svg>
                    </div>
                </ToolbarButton>

                <div className="w-px h-6 bg-gray-200 mx-1 flex-shrink-0" />

                {/* Text Style */}
                <ToolbarButton
                    onClick={() => editor.chain().focus().toggleBold().run()}
                    isActive={editor.isActive('bold')}
                    title="Bold (굵게)"
                >
                    <span className="font-bold text-base select-none leading-none">B</span>
                </ToolbarButton>
                <ToolbarButton
                    onClick={() => editor.chain().focus().toggleItalic().run()}
                    isActive={editor.isActive('italic')}
                    title="Italic (기울임)"
                >
                    <span className="italic font-serif text-base select-none leading-none font-bold">I</span>
                </ToolbarButton>
                <ToolbarButton
                    onClick={() => editor.chain().focus().toggleStrike().run()}
                    isActive={editor.isActive('strike')}
                    title="Strikethrough (취소선)"
                >
                    <span className="line-through text-base select-none leading-none font-bold">S</span>
                </ToolbarButton>
                <ToolbarButton
                    onClick={() => editor.chain().focus().toggleUnderline().run()}
                    isActive={editor.isActive('underline')}
                    title="Underline (밑줄, Ctrl+U)"
                >
                    <span className="underline text-base select-none leading-none font-bold">U</span>
                </ToolbarButton>

                <div className="w-px h-6 bg-gray-200 mx-1" />

                {/* Headings */}
                <ToolbarButton
                    onClick={() => editor.chain().focus().toggleHeading({ level: 1 }).run()}
                    isActive={editor.isActive('heading', { level: 1 })}
                    title="H1"
                >
                    <span className="font-bold text-sm">H1</span>
                </ToolbarButton>
                <ToolbarButton
                    onClick={() => editor.chain().focus().toggleHeading({ level: 2 }).run()}
                    isActive={editor.isActive('heading', { level: 2 })}
                    title="H2"
                >
                    <span className="font-bold text-sm">H2</span>
                </ToolbarButton>
                <ToolbarButton
                    onClick={() => editor.chain().focus().toggleHeading({ level: 3 }).run()}
                    isActive={editor.isActive('heading', { level: 3 })}
                    title="H3"
                >
                    <span className="font-bold text-sm">H3</span>
                </ToolbarButton>

                <div className="w-px h-6 bg-gray-200 mx-1" />

                {/* Lists */}
                <ToolbarButton
                    onClick={() => editor.chain().focus().toggleBulletList().run()}
                    isActive={editor.isActive('bulletList')}
                    title="Bullet List"
                >
                    <svg className="w-5 h-5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M4 6h16M4 12h16M4 18h16" />
                    </svg>
                </ToolbarButton>
                <ToolbarButton
                    onClick={() => editor.chain().focus().toggleOrderedList().run()}
                    isActive={editor.isActive('orderedList')}
                    title="Ordered List"
                >
                    <svg className="w-5 h-5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M7 7h12M7 13h12M7 19h12M3 7v.01M3 13v.01M3 19v.01" />
                    </svg>
                </ToolbarButton>
                <ToolbarButton
                    onClick={() => editor.chain().focus().toggleBlockquote().run()}
                    isActive={editor.isActive('blockquote')}
                    title="Quote"
                >
                    <svg className="w-5 h-5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M7 8h10M7 12h4m1 8l-4-4H5a2 2 0 01-2-2V6a2 2 0 012-2h14a2 2 0 012 2v8a2 2 0 01-2 2h-3l-4 4z" />
                    </svg>
                </ToolbarButton>

                <div className="w-px h-6 bg-gray-200 mx-1" />

                {/* Media */}
                <input
                    type="file"
                    ref={fileInputRef}
                    className="hidden"
                    accept="image/*"
                    onChange={handleImageUpload}
                />
                <button
                    onClick={() => fileInputRef.current?.click()}
                    disabled={isUploading}
                    title="Insert Image from Drive"
                    className={`
                    flex items-center gap-1 px-3 py-1.5 rounded-lg transition-all
                    ${isUploading
                            ? 'bg-gray-100 text-gray-400 cursor-wait'
                            : 'bg-indigo-50 text-indigo-600 hover:bg-indigo-100'
                        }
                `}
                >
                    {isUploading ? (
                        <svg className="animate-spin w-5 h-5" xmlns="http://www.w3.org/2000/svg" fill="none" viewBox="0 0 24 24">
                            <circle className="opacity-25" cx="12" cy="12" r="10" stroke="currentColor" strokeWidth="4"></circle>
                            <path className="opacity-75" fill="currentColor" d="M4 12a8 8 0 018-8V0C5.373 0 0 5.373 0 12h4zm2 5.291A7.962 7.962 0 014 12H0c0 3.042 1.135 5.824 3 7.938l3-2.647z"></path>
                        </svg>
                    ) : (
                        <svg className="w-5 h-5" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                            <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>
                    )}
                    <span className="text-sm font-semibold hidden sm:inline">
                        {isUploading ? '업로드...' : '사진'}
                    </span>
                </button>
            </div>
        </div>
    );
}
