'use client';

import { useState, useEffect } from 'react';
import Link from 'next/link';
import { useRouter } from 'next/navigation';
import { useAuth } from '@/contexts/AuthContext';
import { collection, query, where, getDocs, limit, or, and } from 'firebase/firestore';
import { db } from '@/lib/firebase';
import { COLLECTIONS, Document as WikiDocument } from '@/types/firestore';
import { doc, updateDoc, arrayUnion, serverTimestamp } from 'firebase/firestore';
import { stripMarkdown } from '@/lib/utils/text';
import { toast } from 'sonner';

interface BacklinksPanelProps {
    documentId: string;
    documentTitle: string;
}

export default function BacklinksPanel({ documentId, documentTitle }: BacklinksPanelProps) {
    const { user } = useAuth();
    const [linkedMentions, setLinkedMentions] = useState<WikiDocument[]>([]);
    const [unlinkedMentions, setUnlinkedMentions] = useState<WikiDocument[]>([]);
    const [loading, setLoading] = useState(true);
    const [linkingId, setLinkingId] = useState<string | null>(null);

    const fetchMentions = async () => {
        if (!documentId || !documentTitle || !user) {
            setLoading(false);
            return;
        }

        try {
            setLoading(true);
            const docsRef = collection(db, COLLECTIONS.DOCUMENTS);

            // 1. Linked Mentions (Strict ID-based and Title-based wiki-links)
            const qLinkedIds = query(
                docsRef,
                and(
                    or(
                        where('visibility', '==', 'public'),
                        where('authorId', '==', user.uid)
                    ),
                    where('outgoingLinkIds', 'array-contains', documentId)
                ),
                limit(100)
            );
            const qLinkedTitles = query(
                docsRef,
                and(
                    or(
                        where('visibility', '==', 'public'),
                        where('authorId', '==', user.uid)
                    ),
                    where('outgoingLinks', 'array-contains', documentTitle)
                ),
                limit(20)
            );

            // 2. Unlinked Mentions (Text-based searching using keywords)
            const qUnlinked = query(
                docsRef,
                and(
                    or(
                        where('visibility', '==', 'public'),
                        where('authorId', '==', user.uid)
                    ),
                    where('searchKeywords', 'array-contains', documentTitle.toLowerCase())
                ),
                limit(20)
            );

            const [snapIds, snapTitles, snapUnlinked] = await Promise.all([
                getDocs(qLinkedIds),
                getDocs(qLinkedTitles),
                getDocs(qUnlinked)
            ]);

            // Combine and dedup Linked Mentions
            const linkedMap = new Map<string, WikiDocument>();

            [...snapIds.docs, ...snapTitles.docs].forEach(doc => {
                if (doc.id !== documentId) { // Don't show current doc
                    const data = doc.data() as WikiDocument;
                    const inferredType = data.docType || (data.title.match(/^\d{4}-\d{2}-\d{2}$/) ? 'daily' : 'wiki');
                    linkedMap.set(doc.id, { ...data, id: doc.id, docType: inferredType } as WikiDocument);
                }
            });

            const linkedDocs = Array.from(linkedMap.values());
            setLinkedMentions(linkedDocs);

            // Dedup Unlinked Mentions (Filter out those already in Linked Mentions)
            const unlinkedDocs = snapUnlinked.docs
                .map(doc => {
                    const data = doc.data() as WikiDocument;
                    const inferredType = data.docType || (data.title.match(/^\d{4}-\d{2}-\d{2}$/) ? 'daily' : 'wiki');
                    return { ...data, id: doc.id, docType: inferredType } as WikiDocument;
                })
                .filter(doc => doc.id !== documentId && !linkedMap.has(doc.id));

            setUnlinkedMentions(unlinkedDocs);

        } catch (error) {
            console.error("Error fetching mentions:", error);
        } finally {
            setLoading(false);
        }
    };

    useEffect(() => {
        fetchMentions();
    }, [documentId, documentTitle, user]);

    const handleLinkMention = async (refDoc: WikiDocument) => {
        if (!user || !documentId || !documentTitle || linkingId) return;

        try {
            setLinkingId(refDoc.id);

            const docRef = doc(db, COLLECTIONS.DOCUMENTS, refDoc.id);

            // 1. 본문 변환: "단어" -> "[단어](/docs/ID)" (표준 마크다운 형식)
            const newLink = `[${documentTitle}](/docs/${documentId})`;

            // 특수문자 이스케이프
            const escapedTitle = documentTitle.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');

            // 대소문자 구분 없이 매칭 (이미 링크된 것은 제외)
            const keywordRegex = new RegExp(`(?<!\\[\\[[^|]*|\\([^)]*)${escapedTitle}(?![^\\]]*\\]\\]|[^\\(]*\\))`, 'gi');

            // 모든 매칭 변환
            const newContent = refDoc.content.replace(keywordRegex, newLink);

            if (newContent === refDoc.content) {
                toast.info('연결할 수 있는 텍스트를 찾지 못했습니다.');
                setLinkingId(null);
                return;
            }

            // 2. Firestore 업데이트
            await updateDoc(docRef, {
                content: newContent,
                outgoingLinks: arrayUnion(documentTitle),
                outgoingLinkIds: arrayUnion(documentId),
                updatedAt: serverTimestamp()
            });

            // 3. UI 즉시 갱신 (전체 새로고침 대신 필터링)
            setUnlinkedMentions(prev => prev.filter(d => d.id !== refDoc.id));
            setLinkedMentions(prev => [...prev, { ...refDoc, id: refDoc.id, content: newContent }]);

        } catch (error) {
            console.error('Error linking mention:', error);
            toast.error('연결 중 오류가 발생했습니다.');
        } finally {
            setLinkingId(null);
        }
    };

    if (loading) {
        return <div className="mt-8 text-sm text-gray-400">Loading mentions...</div>;
    }

    if (linkedMentions.length === 0 && unlinkedMentions.length === 0) {
        return null;
    }

    return (
        <div className="mt-12 border-t border-gray-100 pt-8">
            <h2 className="text-xl font-bold text-gray-900 mb-6 flex items-center gap-2">
                <span className="w-1.5 h-6 bg-indigo-600 rounded-full"></span>
                Backlinks
            </h2>

            {linkedMentions.length > 0 && (
                <section className="mb-10">
                    <h3 className="text-sm font-semibold text-gray-400 uppercase tracking-wider mb-4 px-1">
                        Linked Mentions ({linkedMentions.length})
                    </h3>
                    <div className="space-y-3">
                        {linkedMentions.map((doc) => (
                            <MentionCard
                                key={doc.id}
                                doc={doc}
                                keyword={documentTitle}
                                isLinkedMatch={true}
                            />
                        ))}
                    </div>
                </section>
            )}

            {unlinkedMentions.length > 0 && (
                <section>
                    <h3 className="text-sm font-semibold text-gray-400 uppercase tracking-wider mb-4 px-1">
                        POTENTIAL LINKS (MENTIONED) ({unlinkedMentions.length})
                    </h3>
                    <div className="space-y-3">
                        {unlinkedMentions.map((doc) => (
                            <MentionCard
                                key={doc.id}
                                doc={doc}
                                keyword={documentTitle}
                                isUnlinked
                                isLinking={linkingId === doc.id}
                                onLinkMention={() => handleLinkMention(doc)}
                            />
                        ))}
                    </div>
                </section>
            )}
        </div>
    );
}

interface MentionCardProps {
    doc: WikiDocument;
    keyword: string;
    isUnlinked?: boolean;
    isLinking?: boolean;
    isLinkedMatch?: boolean;
    onLinkMention?: () => void;
}

function MentionCard({ doc, keyword, isUnlinked, isLinking, isLinkedMatch, onLinkMention }: MentionCardProps) {
    // 키워드 주변 문맥 추출
    const getContext = (content: string, keyword: string) => {
        const cleanText = stripMarkdown(content);
        if (!cleanText) return "";

        const lowerContent = cleanText.toLowerCase();
        const lowerKeyword = keyword.toLowerCase();
        const index = lowerContent.indexOf(lowerKeyword);

        if (index === -1) return cleanText.slice(0, 150) + "...";

        const start = Math.max(0, index - 60);
        const end = Math.min(cleanText.length, index + keyword.length + 80);
        let excerpt = cleanText.slice(start, end);

        if (start > 0) excerpt = "..." + excerpt;
        if (end < cleanText.length) excerpt = excerpt + "...";

        return excerpt;
    };

    const context = getContext(doc.content, keyword);

    return (
        <Link
            href={`/docs/${doc.id}`}
            className={`block p-5 rounded-xl border border-gray-100 bg-white transition-all group no-underline hover:shadow-lg hover:-translate-y-1 ${doc.docType === 'daily'
                ? 'hover:border-emerald-300 hover:shadow-emerald-100/50'
                : 'hover:border-indigo-300 hover:shadow-indigo-100/50'
                }`}
        >
            <div className="flex items-center justify-between mb-3">
                <div className="flex items-center gap-2">
                    <h4 className={`font-bold text-gray-900 transition-colors m-0 no-underline group-hover:no-underline ${doc.docType === 'daily' ? 'group-hover:text-emerald-600' : 'group-hover:text-indigo-600'
                        }`}>
                        {doc.title}
                    </h4>
                    {/* 문서 타입 배지 */}
                    {doc.docType === 'daily' ? (
                        <span className="text-[10px] px-2 py-0.5 bg-emerald-50 text-emerald-600 rounded-full font-bold border border-emerald-100">
                            Daily
                        </span>
                    ) : (
                        <span className="text-[10px] px-2 py-0.5 bg-indigo-50 text-indigo-600 rounded-full font-bold border border-indigo-100">
                            Wiki
                        </span>
                    )}
                </div>

                <div className="flex items-center gap-2">
                    {/* Status 배지 (오른쪽 정렬로 통일) */}
                    {isLinkedMatch && (
                        <span className="text-[10px] px-2 py-1 bg-green-50 text-green-600 rounded-full font-bold flex items-center gap-1 border border-green-100">
                            <svg className="w-2.5 h-2.5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="3" d="M5 13l4 4L19 7" />
                            </svg>
                            Linked
                        </span>
                    )}

                    {isUnlinked && (
                        <>
                            <button
                                onClick={(e) => {
                                    e.preventDefault();
                                    e.stopPropagation();
                                    if (!isLinking) onLinkMention?.();
                                }}
                                disabled={isLinking}
                                className={`text-[10px] px-3 py-1 ${doc.docType === 'daily' ? 'bg-emerald-500 hover:bg-emerald-600 shadow-emerald-200' : 'bg-indigo-600 hover:bg-indigo-700 shadow-indigo-200'
                                    } text-white rounded-full font-bold transition-all shadow-sm flex items-center gap-1 ${isLinking ? 'opacity-50 cursor-not-allowed' : 'active:scale-95'}`}
                            >
                                {isLinking ? (
                                    <>
                                        <div className="w-2 h-2 border-2 border-white border-t-transparent rounded-full animate-spin"></div>
                                        Linking...
                                    </>
                                ) : (
                                    'Link now'
                                )}
                            </button>
                            <span className="text-[10px] px-2 py-1 bg-gray-100 text-gray-400 rounded-full font-medium">
                                Mentioned
                            </span>
                        </>
                    )}
                </div>
            </div>
            <div className="text-sm text-gray-600 leading-relaxed font-serif m-0">
                {/* 키워드 하이라이팅 처리 (단순 텍스트) */}
                {(() => {
                    const escaped = keyword.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
                    return context.split(new RegExp(`(${escaped})`, 'gi')).map((part, i) => (
                        part.toLowerCase() === keyword.toLowerCase() ? (
                            <mark key={i} className={`font-semibold rounded px-0.5 ${doc.docType === 'daily' ? 'bg-emerald-50 text-emerald-700' : 'bg-indigo-50 text-indigo-700'
                                }`}>
                                {part}
                            </mark>
                        ) : (
                            <span key={i}>{part}</span>
                        )
                    ));
                })()}
            </div>
        </Link>
    );
}
