'use client';

import { useState, useEffect, useRef } from 'react';
import { doc, getDoc } from 'firebase/firestore';
import { db } from '@/lib/firebase';
import { COLLECTIONS, Document as WikiDocument } from '@/types/firestore';
import Link from 'next/link';

interface WikiLinkPreviewProps {
    docId: string;
    label: string;
    children: React.ReactNode;
    visibility?: 'public' | 'private';
}

export default function WikiLinkPreview({ docId, label, children, visibility }: WikiLinkPreviewProps) {
    const [isHovered, setIsHovered] = useState(false);
    const [document, setDocument] = useState<WikiDocument | null>(null);
    const [loading, setLoading] = useState(false);
    const [hasPermission, setHasPermission] = useState(true);
    const [position, setPosition] = useState({ top: 0, left: 0 });
    const linkRef = useRef<HTMLSpanElement>(null);
    const timeoutRef = useRef<NodeJS.Timeout | null>(null);

    // 마우스 진입 시 문서 로드
    const handleMouseEnter = () => {
        timeoutRef.current = setTimeout(() => {
            setIsHovered(true);
            if (!document && !loading) {
                fetchDocument();
            }
        }, 300); // 300ms 딜레이로 실수 호버 방지

        // 팝업 위치 계산
        if (linkRef.current) {
            const rect = linkRef.current.getBoundingClientRect();
            setPosition({
                top: rect.bottom + window.scrollY + 8,
                left: rect.left + window.scrollX,
            });
        }
    };

    const handleMouseLeave = () => {
        if (timeoutRef.current) {
            clearTimeout(timeoutRef.current);
        }
        setIsHovered(false);
    };

    const fetchDocument = async () => {
        if (!docId) return;

        setLoading(true);
        try {
            const docRef = doc(db, COLLECTIONS.DOCUMENTS, docId);
            const docSnap = await getDoc(docRef);

            if (docSnap.exists()) {
                setDocument({ ...docSnap.data() as WikiDocument, id: docSnap.id });
            }
        } catch (error: any) {
            if (error.code === 'permission-denied') {
                setHasPermission(false);
            } else {
                console.error('미리보기 문서 로드 실패:', error);
            }
        } finally {
            setLoading(false);
        }
    };

    // 컨텐츠 미리보기 (첫 150자)
    const getPreviewContent = () => {
        if (!document?.content) return '내용이 없습니다.';

        // 마크다운 문법 간단히 제거
        const plainText = document.content
            .replace(/#{1,6}\s/g, '') // 헤딩 제거
            .replace(/\*\*|__/g, '') // 볼드 제거
            .replace(/\*|_/g, '') // 이탤릭 제거
            .replace(/\[([^\]]+)\]\([^)]+\)/g, '$1') // 링크 텍스트만
            .replace(/`{1,3}[^`]*`{1,3}/g, '') // 코드 제거
            .replace(/\n+/g, ' ') // 줄바꿈을 공백으로
            .trim();

        return plainText.length > 150
            ? plainText.substring(0, 150) + '...'
            : plainText;
    };

    return (
        <span
            ref={linkRef}
            onMouseEnter={handleMouseEnter}
            onMouseLeave={handleMouseLeave}
            className="relative inline"
        >
            {children}

            {/* 미리보기 팝업 */}
            {isHovered && (
                <div
                    className="fixed z-50 w-80 bg-white rounded-xl shadow-2xl border border-gray-200 overflow-hidden animate-in fade-in slide-in-from-top-2 duration-200"
                    style={{
                        top: position.top,
                        left: Math.min(position.left, window.innerWidth - 340),
                    }}
                    onMouseEnter={() => setIsHovered(true)}
                    onMouseLeave={() => setIsHovered(false)}
                >
                    {loading ? (
                        <div className="p-4">
                            <div className="animate-pulse space-y-2">
                                <div className="h-4 bg-gray-200 rounded w-3/4"></div>
                                <div className="h-3 bg-gray-100 rounded w-full"></div>
                                <div className="h-3 bg-gray-100 rounded w-2/3"></div>
                            </div>
                        </div>
                    ) : document ? (
                        <>
                            {/* 헤더 */}
                            <div className="px-4 py-3 bg-gradient-to-r from-indigo-50 to-purple-50 border-b border-gray-100">
                                <h4 className="font-semibold text-gray-900 truncate">
                                    {document.title}
                                </h4>
                                <div className="flex items-center gap-2 mt-1 text-xs text-gray-500">
                                    <span className="px-1.5 py-0.5 bg-indigo-100 text-indigo-700 rounded">
                                        {document.docType === 'wiki' ? 'Wiki' : 'Daily'}
                                    </span>
                                    {document.updatedAt && (
                                        <span>
                                            {new Date(document.updatedAt.seconds * 1000).toLocaleDateString('ko-KR')}
                                        </span>
                                    )}
                                </div>
                            </div>

                            {/* 미리보기 내용 */}
                            <div className="px-4 py-3">
                                <p className="text-sm text-gray-600 leading-relaxed">
                                    {getPreviewContent()}
                                </p>
                            </div>

                            {/* 푸터 */}
                            <div className="px-4 py-2 bg-gray-50 border-t border-gray-100">
                                <Link
                                    href={(document.id.startsWith('new-') || (!document.id && docId.startsWith('new-'))) && visibility
                                        ? `/docs/${docId}?visibility=${visibility}`
                                        : `/docs/${docId}`}
                                    className="text-xs text-indigo-600 hover:text-indigo-800 font-medium flex items-center gap-1"
                                >
                                    전체 문서 보기
                                    <svg className="w-3 h-3" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M9 5l7 7-7 7" />
                                    </svg>
                                </Link>
                            </div>
                        </>
                    ) : !hasPermission ? (
                        <div className="p-4 text-center text-gray-500 text-sm flex flex-col items-center gap-2">
                            <span className="text-xl">🔒</span>
                            <span>비공개 문서입니다</span>
                        </div>
                    ) : (
                        <div className="p-4 text-center text-gray-500 text-sm flex flex-col items-center gap-2">
                            <span className="text-xl">📝</span>
                            <span>새 문서 만들기</span>
                            <div className="mt-2 text-xs text-indigo-600 font-medium">
                                '{label}' 문서가 존재하지 않습니다.<br />
                                클릭하여 생성하세요.
                            </div>
                            <div className="pt-2 w-full border-t border-gray-100 mt-2">
                                <Link
                                    href={visibility ? `/docs/${docId}?visibility=${visibility}` : `/docs/${docId}`}
                                    className="block w-full py-1 text-center text-xs bg-indigo-50 text-indigo-700 rounded hover:bg-indigo-100 transition-colors"
                                >
                                    문서 생성하기
                                </Link>
                            </div>
                        </div>
                    )}
                </div >
            )}
        </span >
    );
}
