'use client';

import { useState, useEffect } from 'react';
import Link from 'next/link';
import { collection, onSnapshot, query, where, orderBy } from 'firebase/firestore';
import { db, auth } from '@/lib/firebase';

interface ProductWithSummary {
    metadata: {
        id: string;
        productId: string;
        companyId: string;
        productName: string;
        companyName: string;
        category: 'life' | 'non_life' | 'variable';
        pageCount?: number;
        effectiveDateRange?: { start: string; end?: string };
        isSalesStopped: boolean;
    };
    summaryJob?: {
        status: 'pending' | 'processing' | 'complete' | 'failed';
        error?: string;
    };
}

type SummaryJobStatus = 'pending' | 'processing' | 'complete' | 'failed';

const statusColors: Record<SummaryJobStatus, string> = {
    pending: 'bg-amber-100 text-amber-700',
    processing: 'bg-blue-100 text-blue-700',
    complete: 'bg-emerald-100 text-emerald-700',
    failed: 'bg-red-100 text-red-700',
};

const statusLabels: Record<SummaryJobStatus, string> = {
    pending: '요약 대기',
    processing: '요약 중',
    complete: '요약 완료',
    failed: '요약 실패',
};

const categoryLabels: Record<string, string> = {
    life: '생명보험',
    non_life: '손해보험',
    variable: '변액보험',
};

export default function InsuranceTermsListClient() {
    const [products, setProducts] = useState<ProductWithSummary[]>([]);
    const [loading, setLoading] = useState(true);
    const [error, setError] = useState<string | null>(null);
    const [filter, setFilter] = useState<'all' | 'life' | 'non_life' | 'variable'>('all');
    const [searchQuery, setSearchQuery] = useState('');
    const [reindexingProductId, setReindexingProductId] = useState<string | null>(null);
    const [reindexResult, setReindexResult] = useState<{ productId: string; success: boolean; message: string } | null>(null);

    useEffect(() => {
        setLoading(true);
        const metaQuery = query(
            collection(db, 'insurance_metadata'),
            where('isActive', '==', true),
            orderBy('updatedAt', 'desc')
        );

        const unsubMeta = onSnapshot(metaQuery, async (snapshot) => {
            const metadataList = snapshot.docs.map(doc => ({
                id: doc.id,
                ...doc.data(),
            }));

            // summary_jobs는 서버 전용이므로 API로 조회 유지
            // 하지만 간단하게 metadata만 실시간으로
            try {
                const res = await fetch('/api/admin/insurance/terms', {
                    headers: { Authorization: `Bearer ${await auth.currentUser?.getIdToken()}` }
                });
                if (res.ok) {
                    const data = await res.json();
                    setProducts(data.products || []);
                }
            } catch (e) {
                // fallback: metadata만 표시
                setProducts(metadataList.map((m: any) => ({ metadata: m, summaryJob: undefined })));
            }
            setLoading(false);
        }, (err) => {
            setError(err.message);
            setLoading(false);
        });

        return () => unsubMeta();
    }, []);

    const handleReindex = async (e: React.MouseEvent, productId: string, productName: string) => {
        e.preventDefault();
        e.stopPropagation();
        if (reindexingProductId) return; // 이미 진행 중

        setReindexingProductId(productId);
        setReindexResult(null);

        try {
            const token = await auth.currentUser?.getIdToken();
            const res = await fetch('/api/admin/insurance/reindex', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                    Authorization: `Bearer ${token}`
                },
                body: JSON.stringify({ productId })
            });

            if (res.ok) {
                const data = await res.json();
                setReindexResult({
                    productId,
                    success: true,
                    message: `${productName} 재인덱싱 요청 완료 (캐시 ${data.cacheCleared || 0}건 삭제)`,
                });
            } else {
                setReindexResult({
                    productId,
                    success: false,
                    message: '재인덱싱 요청 실패',
                });
            }
        } catch (err) {
            setReindexResult({
                productId,
                success: false,
                message: '재인덱싱 요청 실패',
            });
        } finally {
            setReindexingProductId(null);
        }
    };

    const filteredProducts = products.filter(p => {
        const matchesCategory = filter === 'all' || p.metadata.category === filter;
        const matchesSearch = !searchQuery ||
            p.metadata.productName.toLowerCase().includes(searchQuery.toLowerCase()) ||
            p.metadata.companyName.toLowerCase().includes(searchQuery.toLowerCase());
        return matchesCategory && matchesSearch;
    });

    if (loading) {
        return (
            <div className="flex items-center justify-center h-64">
                <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-blue-600"></div>
            </div>
        );
    }

    if (error) {
        return (
            <div className="bg-red-50 border border-red-200 rounded-lg p-4 text-red-700">
                오류: {error}
            </div>
        );
    }

    return (
        <div className="space-y-4">
            {/* 통계 링크 */}
            <div className="flex justify-end">
                <Link href="/admin/terms/stats" className="text-sm text-blue-600 hover:underline">
                    통계 보기
                </Link>
            </div>

            {/* 필터 & 검색 */}
            <div className="flex flex-wrap gap-3 items-center">
                <div className="flex gap-1 bg-slate-100 rounded-lg p-1">
                    {(['all', 'life', 'non_life', 'variable'] as const).map(cat => (
                        <button
                            key={cat}
                            onClick={() => setFilter(cat)}
                            className={`px-3 py-1.5 rounded-md text-sm font-medium transition-colors ${
                                filter === cat
                                    ? 'bg-white shadow text-blue-700'
                                    : 'text-slate-600 hover:text-slate-800'
                            }`}
                        >
                            {cat === 'all' ? '전체' : categoryLabels[cat]}
                        </button>
                    ))}
                </div>
                <input
                    type="text"
                    placeholder="상품명 또는 회사명 검색..."
                    value={searchQuery}
                    onChange={e => setSearchQuery(e.target.value)}
                    className="flex-1 min-w-[200px] px-3 py-2 border border-slate-200 rounded-lg text-sm focus:outline-none focus:ring-2 focus:ring-blue-500"
                />
            </div>

            {/* 목록 */}
            {filteredProducts.length === 0 ? (
                <div className="text-center py-12 text-slate-500">
                    등록된 약관이 없습니다.
                </div>
            ) : (
                <div className="grid gap-3">
                    {filteredProducts.map(p => (
                        <Link
                            key={p.metadata.id}
                            href={`/admin/terms/${p.metadata.id}`}
                            className="block bg-white border border-slate-200 rounded-xl p-4 hover:border-blue-300 hover:shadow-sm transition-all"
                        >
                            <div className="flex items-start justify-between gap-4">
                                <div className="flex-1 min-w-0">
                                    <div className="flex items-center gap-2 mb-1 flex-wrap">
                                        <span className={`text-xs px-2 py-0.5 rounded-full ${
                                            p.metadata.category === 'life' ? 'bg-blue-100 text-blue-700' :
                                            p.metadata.category === 'non_life' ? 'bg-purple-100 text-purple-700' :
                                            'bg-amber-100 text-amber-700'
                                        }`}>
                                            {categoryLabels[p.metadata.category]}
                                        </span>
                                        {p.metadata.isSalesStopped && (
                                            <span className="text-xs px-2 py-0.5 rounded-full bg-slate-100 text-slate-600">
                                                판매중단
                                            </span>
                                        )}
                                        {p.summaryJob && (
                                            <span className={`text-xs px-2 py-0.5 rounded-full ${statusColors[p.summaryJob.status]}`}>
                                                {statusLabels[p.summaryJob.status]}
                                            </span>
                                        )}
                                        {/* OCR 안내 배지 (Item 22) */}
                                        {p.summaryJob?.status === 'failed' && p.summaryJob?.error?.includes('스캔 PDF') && (
                                            <span className="text-xs px-2 py-0.5 rounded-full bg-orange-100 text-orange-700 border border-orange-300">
                                                스캔 PDF - OCR 필요
                                            </span>
                                        )}
                                    </div>
                                    <h3 className="font-semibold text-slate-800 truncate">
                                        {p.metadata.productName}
                                    </h3>
                                    <p className="text-sm text-slate-500">{p.metadata.companyName}</p>
                                    {/* OCR 안내 메시지 (Item 22) */}
                                    {p.summaryJob?.status === 'failed' && p.summaryJob?.error?.includes('스캔 PDF') && (
                                        <p className="text-xs text-orange-600 mt-1">
                                            이 문서는 스캔 PDF입니다. OCR 처리 후 재업로드가 필요합니다.
                                        </p>
                                    )}
                                </div>
                                <div className="flex flex-col items-end gap-2">
                                    <div className="text-right text-xs text-slate-400">
                                        {p.metadata.pageCount && <p>{p.metadata.pageCount}p</p>}
                                        {p.metadata.effectiveDateRange?.start && (
                                            <p>{p.metadata.effectiveDateRange.start}</p>
                                        )}
                                    </div>
                                    {/* CL-7: 원클릭 재인덱싱 버튼 */}
                                    <button
                                        onClick={(e) => handleReindex(e, p.metadata.productId, p.metadata.productName)}
                                        disabled={reindexingProductId === p.metadata.productId}
                                        className={`text-xs px-2.5 py-1 rounded-md transition-colors ${
                                            reindexingProductId === p.metadata.productId
                                                ? 'bg-slate-200 text-slate-400 cursor-not-allowed'
                                                : 'bg-blue-600 text-white hover:bg-blue-700'
                                        }`}
                                    >
                                        {reindexingProductId === p.metadata.productId ? (
                                            <span className="flex items-center gap-1">
                                                <span className="animate-spin inline-block w-3 h-3 border border-slate-400 border-t-transparent rounded-full"></span>
                                                처리 중...
                                            </span>
                                        ) : '재인덱싱'}
                                    </button>
                                    {/* 재인덱싱 결과 메시지 */}
                                    {reindexResult && reindexResult.productId === p.metadata.productId && (
                                        <span className={`text-xs ${reindexResult.success ? 'text-emerald-600' : 'text-red-600'}`}>
                                            {reindexResult.message}
                                        </span>
                                    )}
                                </div>
                            </div>
                        </Link>
                    ))}
                </div>
            )}
        </div>
    );
}
