'use client';

import { useState, useEffect } from 'react';
import { useAuth } from '@/contexts/AuthContext';
import { db } from '@/lib/firebase';
import { collection, query, orderBy, limit, getDocs, Timestamp } from 'firebase/firestore';

interface JobLog {
    id: string;
    status: 'pending' | 'complete' | 'failed';
    queryType?: string;
    createdAt: Timestamp;
    completedAt?: Timestamp;
    tokensUsed?: number;
    error?: string;
}

interface Stats {
    totalJobs: number;
    successJobs: number;
    failedJobs: number;
    totalTokens: number;
    recentJobs: JobLog[];
}

export default function AdminMonitoringPage() {
    const { userRole } = useAuth();
    const [stats, setStats] = useState<Stats | null>(null);
    const [loading, setLoading] = useState(true);

    useEffect(() => {
        if (userRole !== 'admin') return;

        const fetchStats = async () => {
            try {
                // 최근 30일 기준
                const thirtyDaysAgo = new Date();
                thirtyDaysAgo.setDate(thirtyDaysAgo.getDate() - 30);

                const jobsRef = collection(db, 'query_logs');
                const recentQuery = query(
                    jobsRef,
                    orderBy('createdAt', 'desc'),
                    limit(50)
                );

                const snapshot = await getDocs(recentQuery);
                const jobs = snapshot.docs.map(d => ({ id: d.id, ...d.data() } as JobLog));

                const totalJobs = jobs.length;
                const successJobs = jobs.filter(j => j.status === 'complete').length;
                const failedJobs = jobs.filter(j => j.status === 'failed').length;
                const totalTokens = jobs.reduce((acc, j) => acc + (j.tokensUsed || 0), 0);

                setStats({
                    totalJobs,
                    successJobs,
                    failedJobs,
                    totalTokens,
                    recentJobs: jobs.slice(0, 10),
                });
            } catch (err) {
                console.error('Failed to fetch monitoring stats:', err);
                // 데이터 없을 경우 빈 통계
                setStats({
                    totalJobs: 0,
                    successJobs: 0,
                    failedJobs: 0,
                    totalTokens: 0,
                    recentJobs: [],
                });
            } finally {
                setLoading(false);
            }
        };

        fetchStats();
    }, [userRole]);

    if (loading) {
        return (
            <div className="p-8 flex items-center justify-center">
                <div className="animate-spin rounded-full h-8 w-8 border-b-2 border-indigo-600" />
            </div>
        );
    }

    const statCards = [
        {
            label: '총 AI 쿼리 (최근 50건)',
            value: stats?.totalJobs ?? 0,
            color: 'text-gray-900',
            bg: 'bg-gray-50',
        },
        {
            label: '성공',
            value: stats?.successJobs ?? 0,
            color: 'text-green-700',
            bg: 'bg-green-50',
        },
        {
            label: '실패',
            value: stats?.failedJobs ?? 0,
            color: 'text-red-700',
            bg: 'bg-red-50',
        },
        {
            label: '총 토큰 사용량',
            value: stats?.totalTokens ? stats.totalTokens.toLocaleString() : '0',
            color: 'text-indigo-700',
            bg: 'bg-indigo-50',
        },
    ];

    return (
        <div className="p-6 md:p-8 max-w-4xl">
            <div className="mb-6">
                <h1 className="text-2xl font-bold text-gray-900">리소스 모니터링</h1>
                <p className="text-sm text-gray-500 mt-1">AI 쿼리 사용량 및 시스템 상태를 확인합니다.</p>
            </div>

            {/* 통계 카드 */}
            <div className="grid grid-cols-2 md:grid-cols-4 gap-4 mb-8">
                {statCards.map((card) => (
                    <div key={card.label} className={`${card.bg} rounded-xl p-4`}>
                        <p className="text-xs font-medium text-gray-500 mb-1">{card.label}</p>
                        <p className={`text-2xl font-bold ${card.color}`}>{card.value}</p>
                    </div>
                ))}
            </div>

            {/* 시스템 상태 */}
            <div className="bg-white border border-gray-200 rounded-xl p-5 mb-6">
                <h2 className="text-sm font-semibold text-gray-700 mb-4">시스템 상태</h2>
                <div className="space-y-2.5">
                    {[
                        { label: 'Auth (Firebase)', status: '정상' },
                        { label: 'Storage (Google Drive)', status: '정상' },
                        { label: 'Database (Firestore)', status: '정상' },
                        { label: 'AI (Gemini 2.5 Flash)', status: '정상' },
                        { label: 'Cloud Functions (V2)', status: '정상' },
                        { label: 'Deployment (Vercel)', status: '정상' },
                    ].map((item) => (
                        <div key={item.label} className="flex items-center justify-between">
                            <span className="text-sm text-gray-600">{item.label}</span>
                            <span className="flex items-center gap-1.5 text-xs font-medium text-green-700">
                                <span className="w-2 h-2 rounded-full bg-green-500 inline-block" />
                                {item.status}
                            </span>
                        </div>
                    ))}
                </div>
            </div>

            {/* 최근 AI 쿼리 로그 */}
            <div className="bg-white border border-gray-200 rounded-xl p-5">
                <h2 className="text-sm font-semibold text-gray-700 mb-4">최근 AI 쿼리 로그</h2>
                {stats?.recentJobs.length === 0 ? (
                    <p className="text-sm text-gray-400 text-center py-6">
                        아직 기록된 쿼리가 없습니다.<br />
                        <span className="text-xs">query_logs 컬렉션에 데이터가 쌓이면 여기에 표시됩니다.</span>
                    </p>
                ) : (
                    <div className="space-y-2">
                        {stats?.recentJobs.map((job) => (
                            <div key={job.id} className="flex items-center gap-3 py-2 border-b border-gray-100 last:border-0">
                                <span className={`w-2 h-2 rounded-full flex-shrink-0 ${
                                    job.status === 'complete' ? 'bg-green-500' :
                                    job.status === 'failed' ? 'bg-red-500' : 'bg-yellow-400'
                                }`} />
                                <span className="text-xs text-gray-500 font-mono flex-shrink-0">
                                    {job.id.slice(0, 8)}...
                                </span>
                                <span className="text-xs text-gray-700 flex-1 truncate">
                                    {job.queryType ?? '약관 쿼리'}
                                </span>
                                {job.tokensUsed && (
                                    <span className="text-xs text-gray-400 flex-shrink-0">
                                        {job.tokensUsed.toLocaleString()} tokens
                                    </span>
                                )}
                                <span className="text-xs text-gray-400 flex-shrink-0">
                                    {job.createdAt?.toDate?.()?.toLocaleDateString('ko-KR')}
                                </span>
                            </div>
                        ))}
                    </div>
                )}
            </div>
        </div>
    );
}
