'use client';

import { useState, useEffect } from 'react';
import Link from 'next/link';
import { COLLECTIONS, InsuranceMetadata, SummaryJob, SummaryJobStatus } from '@/types/firestore';

interface ProductWithSummary {
    metadata: InsuranceMetadata;
    summaryJob?: SummaryJob;
}

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 InsuranceTermsList() {
    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('');

    useEffect(() => {
        async function fetchProducts() {
            try {
                setLoading(true);
                const res = await fetch('/api/admin/insurance/terms');
                if (!res.ok) throw new Error('데이터 로드 실패');
                const data = await res.json();
                setProducts(data.products || []);
            } catch (e) {
                setError(e instanceof Error ? e.message : '알 수 없는 오류');
            } finally {
                setLoading(false);
            }
        }
        fetchProducts();
    }, []);

    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 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">
                                        <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>
                                        )}
                                    </div>
                                    <h3 className="font-semibold text-slate-800 truncate">
                                        {p.metadata.productName}
                                    </h3>
                                    <p className="text-sm text-slate-500">{p.metadata.companyName}</p>
                                </div>
                                <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>
                            </div>
                        </Link>
                    ))}
                </div>
            )}
        </div>
    );
}
