'use client';

/**
 * HubDocuments 컴포넌트
 * 
 * 가장 많이 참조되는 문서(백링크 허브)를 표시합니다.
 * 다른 문서에서 가장 많이 링크된 문서들을 상위 N개 보여줍니다.
 */

import { useState, useEffect } from 'react';
import { collection, query, where, getDocs, orderBy, limit } from 'firebase/firestore';
import { db } from '@/lib/firebase';
import { COLLECTIONS, Document as WikiDocument } from '@/types/firestore';
import { useAuth } from '@/contexts/AuthContext';
import Link from 'next/link';

interface HubDocument extends WikiDocument {
    incomingLinkCount: number;
}

interface HubDocumentsProps {
    maxItems?: number;
}

export default function HubDocuments({ maxItems = 5 }: HubDocumentsProps) {
    const { user } = useAuth();
    const [hubDocs, setHubDocs] = useState<HubDocument[]>([]);
    const [loading, setLoading] = useState(true);

    useEffect(() => {
        if (!user) return;

        const fetchHubDocuments = async () => {
            try {
                const docsRef = collection(db, COLLECTIONS.DOCUMENTS);

                // 1차: 서버 집계 필드(incomingLinkCount) 기반 쿼리 (읽기 5건)
                const serverQuery = query(
                    docsRef,
                    where('docType', '==', 'wiki'),
                    where('visibility', '==', 'public'),
                    where('incomingLinkCount', '>', 0),
                    orderBy('incomingLinkCount', 'desc'),
                    limit(maxItems)
                );
                const serverSnapshot = await getDocs(serverQuery);

                if (!serverSnapshot.empty) {
                    // 서버 집계값이 존재하면 바로 사용
                    const hubDocuments: HubDocument[] = [];
                    serverSnapshot.forEach((docSnap) => {
                        const data = docSnap.data() as WikiDocument;
                        hubDocuments.push({
                            ...data,
                            id: docSnap.id,
                            incomingLinkCount: data.incomingLinkCount || 0
                        });
                    });
                    setHubDocs(hubDocuments);
                } else {
                    // 폴백: 서버 집계값이 아직 없으면 클라이언트에서 계산
                    const fallbackQuery = query(
                        docsRef,
                        where('docType', '==', 'wiki'),
                        where('visibility', '==', 'public')
                    );
                    const querySnapshot = await getDocs(fallbackQuery);

                    const docs: WikiDocument[] = [];
                    querySnapshot.forEach((docSnap) => {
                        docs.push({ ...docSnap.data() as WikiDocument, id: docSnap.id });
                    });

                    // 각 문서가 다른 문서에서 몇 번 참조되는지 계산
                    const linkCountMap: Record<string, number> = {};

                    docs.forEach(doc => {
                        doc.outgoingLinkIds?.forEach(linkId => {
                            linkCountMap[linkId] = (linkCountMap[linkId] || 0) + 1;
                        });
                        doc.outgoingLinks?.forEach(linkTitle => {
                            const targetDoc = docs.find(d => d.title === linkTitle);
                            if (targetDoc) {
                                linkCountMap[targetDoc.id] = (linkCountMap[targetDoc.id] || 0) + 1;
                            }
                        });
                    });

                    const hubDocuments: HubDocument[] = docs
                        .map(doc => ({
                            ...doc,
                            incomingLinkCount: linkCountMap[doc.id] || 0
                        }))
                        .filter(doc => doc.incomingLinkCount > 0)
                        .sort((a, b) => b.incomingLinkCount - a.incomingLinkCount)
                        .slice(0, maxItems);

                    setHubDocs(hubDocuments);
                }
            } catch (error) {
                console.error('Hub 문서 로딩 실패:', error);
            } finally {
                setLoading(false);
            }
        };

        fetchHubDocuments();
    }, [user, maxItems]);

    if (loading) {
        return (
            <div className="bg-white rounded-2xl shadow-sm border border-gray-100 p-6">
                <div className="animate-pulse space-y-3">
                    <div className="h-5 bg-gray-200 rounded w-1/3"></div>
                    <div className="h-4 bg-gray-100 rounded w-full"></div>
                    <div className="h-4 bg-gray-100 rounded w-3/4"></div>
                </div>
            </div>
        );
    }

    if (hubDocs.length === 0) {
        return null; // 허브 문서가 없으면 섹션 숨김
    }

    return (
        <div className="bg-gradient-to-br from-indigo-50/50 to-purple-50/50 rounded-2xl shadow-sm border border-indigo-100/50 p-6">
            <div className="flex items-center gap-2 mb-5">
                <div className="p-2 bg-indigo-100 rounded-xl">
                    <svg className="w-5 h-5 text-indigo-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                        <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M13.828 10.172a4 4 0 00-5.656 0l-4 4a4 4 0 105.656 5.656l1.102-1.101m-.758-4.899a4 4 0 005.656 0l4-4a4 4 0 00-5.656-5.656l-1.1 1.1" />
                    </svg>
                </div>
                <h3 className="text-lg font-bold text-gray-900">📌 자주 연결되는 허브 문서</h3>
            </div>

            <div className="space-y-3">
                {hubDocs.map((doc, index) => (
                    <Link
                        key={doc.id}
                        href={`/docs/${doc.id}`}
                        className="flex items-center justify-between p-3 bg-white/80 rounded-xl hover:bg-white hover:shadow-md transition-all group"
                    >
                        <div className="flex items-center gap-3 min-w-0">
                            <span className={`flex-shrink-0 w-6 h-6 rounded-full flex items-center justify-center text-xs font-bold ${index === 0 ? 'bg-amber-100 text-amber-700' :
                                index === 1 ? 'bg-gray-200 text-gray-600' :
                                    index === 2 ? 'bg-orange-100 text-orange-700' :
                                        'bg-gray-100 text-gray-500'
                                }`}>
                                {index + 1}
                            </span>
                            <span className="text-sm font-medium text-gray-800 truncate group-hover:text-indigo-600 transition-colors">
                                {doc.title}
                            </span>
                        </div>
                        <div className="flex items-center gap-1.5 flex-shrink-0">
                            <svg className="w-4 h-4 text-indigo-400" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M13.828 10.172a4 4 0 00-5.656 0l-4 4a4 4 0 105.656 5.656l1.102-1.101" />
                            </svg>
                            <span className="text-xs font-bold text-indigo-600 bg-indigo-50 px-2 py-0.5 rounded-full">
                                {doc.incomingLinkCount}
                            </span>
                        </div>
                    </Link>
                ))}
            </div>
        </div>
    );
}
