'use client';

import { useState, useEffect } from 'react';
import { InsuranceSummary, InsuranceChunk, SummaryLevel } from '@/types/firestore';
import Level1Card from './Level1Card';
import Level2Accordion from './Level2Accordion';
import Level3Search from './Level3Search';

type TabLevel = 1 | 2 | 3;

interface TermSummaryViewProps {
    productId: string;
    companyId: string;
    productName: string;
    companyName: string;
}

export default function TermSummaryView({ 
    productId, 
    companyId,
    productName,
    companyName 
}: TermSummaryViewProps) {
    const [activeLevel, setActiveLevel] = useState<TabLevel>(1);
    const [loading, setLoading] = useState(true);
    const [error, setError] = useState<string | null>(null);
    
    // Level 1 요약
    const [level1Summary, setLevel1Summary] = useState<InsuranceSummary | null>(null);
    
    // Level 2 섹션 요약들
    const [level2Summaries, setLevel2Summaries] = useState<InsuranceSummary[]>([]);
    
    // Level 3 청크 수
    const [chunksCount, setChunksCount] = useState(0);

    useEffect(() => {
        async function fetchSummaries() {
            try {
                setLoading(true);
                const res = await fetch(`/api/admin/insurance/terms/${productId}/summaries`);
                if (!res.ok) throw new Error('요약 데이터 로드 실패');
                const data = await res.json();
                
                // Level 1 요약 (하나만)
                const l1 = data.summaries?.find((s: InsuranceSummary) => s.level === 1);
                setLevel1Summary(l1 || null);
                
                // Level 2 섹션 요약들 (여러 개)
                const l2 = data.summaries?.filter((s: InsuranceSummary) => s.level === 2) || [];
                setLevel2Summaries(l2);
                
                // 청크 수
                setChunksCount(data.chunksCount || 0);
            } catch (e) {
                setError(e instanceof Error ? e.message : '알 수 없는 오류');
            } finally {
                setLoading(false);
            }
        }
        fetchSummaries();
    }, [productId]);

    if (loading) {
        return (
            <div className="flex items-center justify-center h-48">
                <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="bg-gradient-to-r from-blue-600 to-purple-600 text-white rounded-xl p-5">
                <h1 className="text-xl font-bold">{productName}</h1>
                <p className="text-sm opacity-80">{companyName}</p>
            </div>

            {/* Level 탭 */}
            <div className="flex border-b border-slate-200">
                {[
                    { level: 1 as TabLevel, label: '핵심 요약', icon: '💡', desc: '전체 핵심 내용' },
                    { level: 2 as TabLevel, label: '섹션별 요약', icon: '📑', desc: `${level2Summaries.length}개 섹션` },
                    { level: 3 as TabLevel, label: '원문 검색', icon: '🔍', desc: `${chunksCount}개 청크` },
                ].map(tab => (
                    <button
                        key={tab.level}
                        onClick={() => setActiveLevel(tab.level)}
                        className={`flex-1 py-3 px-4 text-center transition-colors relative ${
                            activeLevel === tab.level
                                ? 'text-blue-700 font-semibold'
                                : 'text-slate-500 hover:text-slate-700'
                        }`}
                    >
                        <div className="flex items-center justify-center gap-2">
                            <span>{tab.icon}</span>
                            <span>{tab.label}</span>
                        </div>
                        <p className="text-xs mt-0.5 opacity-70">{tab.desc}</p>
                        {activeLevel === tab.level && (
                            <div className="absolute bottom-0 left-0 right-0 h-0.5 bg-blue-600"></div>
                        )}
                    </button>
                ))}
            </div>

            {/* Level별 컨텐츠 */}
            <div className="min-h-[300px]">
                {activeLevel === 1 && (
                    <Level1Card 
                        summary={level1Summary}
                        productId={productId}
                    />
                )}
                
                {activeLevel === 2 && (
                    <Level2Accordion 
                        summaries={level2Summaries}
                        productId={productId}
                    />
                )}
                
                {activeLevel === 3 && (
                    <Level3Search 
                        productId={productId}
                        chunksCount={chunksCount}
                    />
                )}
            </div>
        </div>
    );
}
