'use client';

import { useState, useEffect } from 'react';
import { InsuranceChunk } from '@/types/firestore';

interface Level3SearchProps {
    productId: string;
    chunksCount: number;
}

interface SearchResult {
    chunk: InsuranceChunk;
    score: number;
    highlightedText: string;
}

export default function Level3Search({ productId, chunksCount }: Level3SearchProps) {
    const [query, setQuery] = useState('');
    const [results, setResults] = useState<SearchResult[]>([]);
    const [loading, setLoading] = useState(false);
    const [error, setError] = useState<string | null>(null);
    const [selectedChunk, setSelectedChunk] = useState<InsuranceChunk | null>(null);
    const [pageInput, setPageInput] = useState('');
    const [pageChunks, setPageChunks] = useState<InsuranceChunk[]>([]);

    // 검색 실행
    const handleSearch = async () => {
        if (!query.trim()) return;
        
        setLoading(true);
        setError(null);
        setSelectedChunk(null);
        
        try {
            const res = await fetch(`/api/admin/insurance/terms/${productId}/search`, {
                method: 'POST',
                headers: { 'Content-Type': 'application/json' },
                body: JSON.stringify({ query: query.trim() })
            });
            
            if (!res.ok) throw new Error('검색 실패');
            const data = await res.json();
            setResults(data.results || []);
        } catch (e) {
            setError(e instanceof Error ? e.message : '검색 중 오류 발생');
        } finally {
            setLoading(false);
        }
    };

    // 페이지로 이동
    const handleGoToPage = async () => {
        const pageNum = parseInt(pageInput);
        if (isNaN(pageNum) || pageNum < 1) return;
        
        setLoading(true);
        setError(null);
        
        try {
            const res = await fetch(`/api/admin/insurance/terms/${productId}/chunks?page=${pageNum}`);
            if (!res.ok) throw new Error('페이지 조회 실패');
            const data = await res.json();
            setPageChunks(data.chunks || []);
        } catch (e) {
            setError(e instanceof Error ? e.message : '페이지 조회 중 오류');
        } finally {
            setLoading(false);
        }
    };

    // HTML 특수문자 이스케이프 (XSS 방지)
    const escapeHtml = (str: string): string =>
        str.replace(/&/g, '&amp;').replace(/</g, '&lt;').replace(/>/g, '&gt;').replace(/"/g, '&quot;');

    // 텍스트 하이라이트 (HTML 이스케이프 후 마크 삽입)
    const highlightText = (text: string, query: string): string => {
        const escaped = escapeHtml(text);
        if (!query) return escaped;
        const escapedQuery = query.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
        const regex = new RegExp(`(${escapedQuery})`, 'gi');
        return escaped.replace(regex, '<mark class="bg-yellow-200">$1</mark>');
    };

    return (
        <div className="space-y-4">
            {/* 검색 입력 */}
            <div className="flex gap-2">
                <div className="flex-1 relative">
                    <input
                        type="text"
                        value={query}
                        onChange={e => setQuery(e.target.value)}
                        onKeyDown={e => e.key === 'Enter' && handleSearch()}
                        placeholder="약관 내용 검색... (예: 사망보험금, 면책사항)"
                        className="w-full px-4 py-3 pr-10 border border-slate-200 rounded-xl text-sm focus:outline-none focus:ring-2 focus:ring-blue-500"
                    />
                    <button
                        onClick={handleSearch}
                        disabled={loading || !query.trim()}
                        className="absolute right-2 top-1/2 -translate-y-1/2 p-1.5 rounded-lg bg-blue-600 text-white disabled:opacity-50 disabled:cursor-not-allowed"
                    >
                        <svg className="w-4 h-4" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M21 21l-6-6m2-5a7 7 0 11-14 0 7 7 0 0114 0z" />
                        </svg>
                    </button>
                </div>
            </div>

            {/* 페이지 이동 */}
            <div className="flex items-center gap-2">
                <span className="text-sm text-slate-500">페이지로 이동:</span>
                <input
                    type="number"
                    value={pageInput}
                    onChange={e => setPageInput(e.target.value)}
                    onKeyDown={e => e.key === 'Enter' && handleGoToPage()}
                    placeholder="페이지 번호"
                    className="w-24 px-3 py-1.5 border border-slate-200 rounded-lg text-sm"
                />
                <button
                    onClick={handleGoToPage}
                    className="px-3 py-1.5 bg-slate-100 text-slate-700 rounded-lg text-sm hover:bg-slate-200"
                >
                    이동
                </button>
            </div>

            {/* 통계 */}
            <div className="bg-slate-50 border border-slate-200 rounded-lg px-4 py-2 text-sm text-slate-600">
                총 <span className="font-semibold text-slate-800">{chunksCount}</span>개 청크 검색 가능
            </div>

            {/* 에러 */}
            {error && (
                <div className="bg-red-50 border border-red-200 rounded-lg p-3 text-sm text-red-700">
                    {error}
                </div>
            )}

            {/* 로딩 */}
            {loading && (
                <div className="flex items-center justify-center py-8">
                    <div className="animate-spin rounded-full h-6 w-6 border-b-2 border-blue-600"></div>
                </div>
            )}

            {/* 검색 결과 */}
            {!loading && results.length > 0 && (
                <div className="space-y-3">
                    <h4 className="text-sm font-semibold text-slate-700">
                        검색 결과 ({results.length}건)
                    </h4>
                    <div className="divide-y divide-slate-200 border border-slate-200 rounded-xl overflow-hidden">
                        {results.map((result, index) => (
                            <div 
                                key={index}
                                onClick={() => setSelectedChunk(result.chunk)}
                                className={`p-4 cursor-pointer transition-colors ${
                                    selectedChunk === result.chunk ? 'bg-blue-50' : 'bg-white hover:bg-slate-50'
                                }`}
                            >
                                <div className="flex items-start justify-between gap-3">
                                    <div className="flex-1 min-w-0">
                                        <div className="flex items-center gap-2 mb-1">
                                            <span className="text-xs bg-slate-100 text-slate-600 px-2 py-0.5 rounded">
                                                {result.chunk.pageNumber}p
                                            </span>
                                            <span className="text-xs text-slate-400">
                                                유사도: {(result.score * 100).toFixed(1)}%
                                            </span>
                                        </div>
                                        <p 
                                            className="text-sm text-slate-700 line-clamp-3"
                                            dangerouslySetInnerHTML={{ 
                                                __html: highlightText(result.chunk.chunkText.slice(0, 200), query) 
                                            }}
                                        />
                                    </div>
                                </div>
                            </div>
                        ))}
                    </div>
                </div>
            )}

            {/* 페이지 조회 결과 */}
            {!loading && pageChunks.length > 0 && (
                <div className="space-y-3">
                    <h4 className="text-sm font-semibold text-slate-700">
                        페이지 {pageInput} 내용
                    </h4>
                    <div className="divide-y divide-slate-200 border border-slate-200 rounded-xl overflow-hidden">
                        {pageChunks.map((chunk, index) => (
                            <div key={index} className="p-4 bg-white">
                                <p className="text-sm text-slate-700 whitespace-pre-wrap">
                                    {chunk.chunkText}
                                </p>
                            </div>
                        ))}
                    </div>
                </div>
            )}

            {/* 선택된 청크 상세 */}
            {selectedChunk && (
                <div className="fixed inset-0 bg-black/50 flex items-center justify-center z-50 p-4">
                    <div className="bg-white rounded-2xl max-w-2xl w-full max-h-[80vh] overflow-hidden flex flex-col">
                        <div className="flex items-center justify-between px-5 py-4 border-b border-slate-200">
                            <div className="flex items-center gap-3">
                                <span className="text-lg font-semibold text-slate-800">
                                    {selectedChunk.pageNumber}p
                                </span>
                                <span className="text-sm text-slate-500">
                                    {selectedChunk.productName}
                                </span>
                            </div>
                            <button
                                onClick={() => setSelectedChunk(null)}
                                className="p-1.5 rounded-lg hover:bg-slate-100"
                            >
                                <svg className="w-5 h-5 text-slate-500" fill="none" viewBox="0 0 24 24" stroke="currentColor">
                                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth={2} d="M6 18L18 6M6 6l12 12" />
                                </svg>
                            </button>
                        </div>
                        <div className="flex-1 overflow-y-auto p-5">
                            <p className="text-slate-700 leading-relaxed whitespace-pre-wrap">
                                {selectedChunk.chunkText}
                            </p>
                        </div>
                    </div>
                </div>
            )}

            {/* 빈 상태 */}
            {!loading && results.length === 0 && pageChunks.length === 0 && (
                <div className="text-center py-12 text-slate-500">
                    <p>검색어를 입력하고 엔터를 눌러주세요</p>
                    <p className="text-sm mt-1">또는 페이지 번호로 이동할 수 있습니다</p>
                </div>
            )}
        </div>
    );
}
