'use client';

import { Document as WikiDocument } from '@/types/firestore';
import { stripMarkdown } from '@/lib/utils/text';

// 검색어 하이라이팅 컴포넌트
function HighlightText({ text, query }: { text: string; query: string }) {
    if (!query.trim() || query.length < 2) {
        return <>{text}</>;
    }

    const regex = new RegExp(`(${query.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')})`, 'gi');
    const parts = text.split(regex);

    return (
        <>
            {parts.map((part, i) =>
                regex.test(part) ? (
                    <mark key={i} className="bg-yellow-200 text-yellow-900 px-0.5 rounded">{part}</mark>
                ) : (
                    <span key={i}>{part}</span>
                )
            )}
        </>
    );
}

// 상대 날짜 계산 함수
function getRelativeDate(date: Date): string {
    const now = new Date();
    const diffTime = now.getTime() - date.getTime();
    const diffDays = Math.floor(diffTime / (1000 * 60 * 60 * 24));

    if (diffDays === 0) return '오늘';
    if (diffDays === 1) return '어제';
    if (diffDays < 7) return `${diffDays}일 전`;
    if (diffDays < 30) return `${Math.floor(diffDays / 7)}주 전`;
    return `${Math.floor(diffDays / 30)}개월 전`;
}

interface NormalResultsProps {
    loading: boolean;
    results: WikiDocument[];
    searchQuery: string;
    selectedIndex: number;
    onSelect: (docId: string) => void;
}

export default function NormalResults({ loading, results, searchQuery, selectedIndex, onSelect }: NormalResultsProps) {
    const getDocType = (doc: WikiDocument) => {
        return doc.docType || (doc.title.match(/^\d{4}-\d{2}-\d{2}$/) ? 'daily' : 'wiki');
    };

    if (loading) {
        return (
            <div className="p-10 text-center">
                <div className="inline-block w-8 h-8 border-3 border-indigo-600 border-t-transparent rounded-full animate-spin"></div>
                <p className="mt-3 text-sm text-gray-500">지식을 탐색하는 중...</p>
            </div>
        );
    }

    if (results.length > 0) {
        return (
            <div className="space-y-1">
                {results.map((doc, index) => {
                    const docType = getDocType(doc);
                    const isDaily = docType === 'daily';
                    const isSelected = index === selectedIndex;
                    const updatedAt = doc.updatedAt?.toDate?.() || new Date();

                    return (
                        <button
                            key={doc.id}
                            className={`w-full text-left px-4 py-3 flex items-start gap-4 transition-all duration-150 rounded-2xl ${isSelected
                                ? 'bg-indigo-50/80 shadow-sm translate-x-1'
                                : 'hover:bg-gray-50/80'
                                }`}
                            onClick={() => onSelect(doc.id)}
                            role="option"
                            aria-selected={isSelected}
                        >
                            <div className="text-lg mt-0.5">
                                {isDaily ? '📅' : '📄'}
                            </div>
                            <div className="flex-1 min-w-0">
                                <div className="flex items-center gap-2">
                                    <h3 className="text-sm font-bold text-gray-900 truncate">
                                        <HighlightText text={doc.title} query={searchQuery} />
                                    </h3>
                                    {isSelected && (
                                        <span className="text-[10px] bg-indigo-100 text-indigo-600 px-1.5 py-0.5 rounded font-bold flex-shrink-0">
                                            ↵ 이동
                                        </span>
                                    )}
                                </div>
                                <p className="text-xs text-gray-400 mt-0.5 truncate">
                                    {stripMarkdown(doc.content || '').slice(0, 80)}
                                </p>
                                <div className="flex items-center gap-2 mt-1">
                                    <span className="text-[10px] text-gray-300">{getRelativeDate(updatedAt)}</span>
                                    {doc.category && (
                                        <span className="text-[10px] bg-gray-100 text-gray-400 px-1.5 py-0.5 rounded-full">
                                            {doc.category}
                                        </span>
                                    )}
                                </div>
                            </div>
                        </button>
                    );
                })}
            </div>
        );
    }

    if (searchQuery.trim()) {
        return (
            <div className="p-10 text-center text-slate-400">
                <div className="text-4xl mb-3 opacity-50">🔍</div>
                <p className="text-sm font-bold">검색 결과가 없습니다</p>
                <p className="text-xs mt-1">다른 키워드로 검색해 보세요</p>
            </div>
        );
    }

    return null;
}
