'use client';

/**
 * TrashClient.tsx
 * 휴지통 클라이언트 컴포넌트
 * [2026-02-24] 최초 작성
 * - 본인 삭제 문서 목록 (일반 사용자)
 * - 전체 삭제 문서 목록 (관리자)
 * - 복원 / 영구삭제 기능
 */

import { useEffect, useState } from 'react';
import {
    collection, query, where, orderBy, limit,
    getDocs, doc, updateDoc, serverTimestamp
} from 'firebase/firestore';
import { db } from '@/lib/firebase';
import { useAuth } from '@/contexts/AuthContext';
import { useRouter } from 'next/navigation';
import GlobalHeader from '@/components/GlobalHeader';
import Link from 'next/link';
import { ADMIN_EMAILS, formatAuthorName } from '@/lib/constants';
import { toast } from 'sonner';
import { confirmDialog } from '@/lib/confirm';

interface TrashDoc {
    id: string;
    title: string;
    docType?: string;
    visibility?: string;
    authorId?: string;
    authorName?: string;
    deletedAt?: { toDate: () => Date } | null;
    deletedBy?: string;
}

export default function TrashClient() {
    const { user, loading } = useAuth();
    const router = useRouter();
    const [docs, setDocs] = useState<TrashDoc[]>([]);
    const [isLoading, setIsLoading] = useState(true);
    const [actionId, setActionId] = useState<string | null>(null);

    const isAdmin = !!(user?.email && ADMIN_EMAILS.includes(user.email));

    // 비로그인 리다이렉트
    useEffect(() => {
        if (!loading && !user) router.push('/login');
    }, [user, loading, router]);

    // 삭제 문서 조회
    useEffect(() => {
        if (!user) return;
        fetchTrash();
    }, [user]);

    const fetchTrash = async () => {
        if (!user) return;
        setIsLoading(true);
        try {
            let q;
            if (isAdmin) {
                // 관리자: 전체 삭제 문서 (복합 인덱스 오류 방지를 위해 orderBy 제거)
                q = query(
                    collection(db, 'documents'),
                    where('isDeleted', '==', true),
                    limit(200)
                );
            } else {
                // 일반 유저: 본인 삭제 문서만 (복합 인덱스 오류 방지를 위해 orderBy 제거)
                q = query(
                    collection(db, 'documents'),
                    where('isDeleted', '==', true),
                    where('authorId', '==', user.uid),
                    limit(200)
                );
            }
            const snapshot = await getDocs(q);
            const result: TrashDoc[] = [];
            snapshot.forEach((d) => {
                result.push({ id: d.id, ...d.data() } as TrashDoc);
            });
            // 클라이언트 사이드 정렬 (최신 삭제순)
            result.sort((a, b) => {
                const dateA = a.deletedAt?.toDate()?.getTime() || 0;
                const dateB = b.deletedAt?.toDate()?.getTime() || 0;
                return dateB - dateA;
            });
            setDocs(result);
        } catch (error) {
            console.error('[Trash] 조회 실패:', error);
        } finally {
            setIsLoading(false);
        }
    };

    // 복원
    const handleRestore = async (docId: string, title: string) => {
        if (!(await confirmDialog(`"${title}" 문서를 복원하시겠습니까?`))) return;
        setActionId(docId);
        try {
            await updateDoc(doc(db, 'documents', docId), {
                isDeleted: false,
                deletedAt: null,
                deletedBy: null,
                updatedAt: serverTimestamp(),
            });
            setDocs(prev => prev.filter(d => d.id !== docId));
        } catch (e) {
            console.error('[Trash] 복원 실패:', e);
            toast.error('복원 중 오류가 발생했습니다.');
        } finally {
            setActionId(null);
        }
    };

    // 영구삭제 (관리자 또는 본인 작성 문서)
    const handlePurge = async (docId: string, title: string) => {
        // 이미 렌더링 시점에서 본인 문서만 보이거나 관리자이므로, 추가 권한 검증은 API에 위임
        if (!(await confirmDialog(`경고: "${title}" 문서를 영구적으로 삭제하시겠습니까?\n이 작업은 되돌릴 수 없습니다.`))) return;
        setActionId(docId);
        try {
            const token = await user!.getIdToken();
            const res = await fetch(`/api/admin/purge?docId=${docId}`, {
                method: 'DELETE',
                headers: { Authorization: `Bearer ${token}` },
            });
            if (!res.ok) {
                const data = await res.json();
                throw new Error(data.error || 'Purge failed');
            }
            setDocs(prev => prev.filter(d => d.id !== docId));
        } catch (e: unknown) {
            const msg = e instanceof Error ? e.message : '오류 발생';
            toast.error(`영구 삭제 실패: ${msg}`);
        } finally {
            setActionId(null);
        }
    };

    const formatDate = (deletedAt: TrashDoc['deletedAt']) => {
        if (!deletedAt) return '날짜 미상';
        try {
            const d = deletedAt.toDate();
            return d.toLocaleDateString('ko-KR', { year: 'numeric', month: 'short', day: 'numeric', hour: '2-digit', minute: '2-digit' });
        } catch { return '날짜 미상'; }
    };

    const getTypeLabel = (d: TrashDoc) => {
        if (d.id.startsWith('daily-') || d.docType === 'daily') return { label: 'Daily', cls: 'bg-emerald-50 text-emerald-600 border-emerald-100' };
        if (d.visibility === 'private') return { label: 'My', cls: 'bg-violet-50 text-violet-600 border-violet-100' };
        return { label: 'Wiki', cls: 'bg-indigo-50 text-indigo-600 border-indigo-100' };
    };

    if (loading || (!user && !loading)) {
        return (
            <div className="min-h-screen flex items-center justify-center bg-gray-50">
                <div className="animate-spin rounded-full h-8 w-8 border-t-2 border-b-2 border-red-500" />
            </div>
        );
    }

    return (
        <div className="min-h-screen bg-gray-50">
            <GlobalHeader variant="wiki" onTabChange={(tab) => router.push(`/?tab=${tab}`)} />

            <main className="max-w-4xl mx-auto px-4 sm:px-6 lg:px-8 py-8">
                {/* 헤더 */}
                <div className="mb-8">
                    <div className="flex items-center gap-3 mb-2">
                        <div className="p-2.5 bg-red-100 rounded-xl">
                            <svg className="w-6 h-6 text-red-500" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16" />
                            </svg>
                        </div>
                        <div>
                            <h1 className="text-2xl font-bold text-gray-900">휴지통</h1>
                            <p className="text-sm text-gray-500 mt-0.5">
                                {isAdmin ? '전체 삭제된 문서 목록입니다' : '내가 삭제한 문서 목록입니다'} — 복원 또는 영구 삭제할 수 있습니다
                            </p>
                        </div>
                    </div>
                    {isAdmin && (
                        <div className="mt-3 inline-flex items-center gap-1.5 px-3 py-1 bg-red-50 text-red-600 text-xs font-semibold rounded-full border border-red-100">
                            <svg className="w-3.5 h-3.5" fill="currentColor" viewBox="0 0 20 20">
                                <path fillRule="evenodd" d="M18 10a8 8 0 11-16 0 8 8 0 0116 0zm-7-4a1 1 0 11-2 0 1 1 0 012 0zM9 9a1 1 0 000 2v3a1 1 0 001 1h1a1 1 0 100-2v-3a1 1 0 00-1-1H9z" clipRule="evenodd" />
                            </svg>
                            관리자 모드 — 전체 문서 표시 중
                        </div>
                    )}
                </div>

                {/* 로딩 */}
                {isLoading && (
                    <div className="flex items-center justify-center py-20">
                        <div className="animate-spin rounded-full h-8 w-8 border-t-2 border-b-2 border-red-400" />
                    </div>
                )}

                {/* 빈 상태 */}
                {!isLoading && docs.length === 0 && (
                    <div className="bg-white rounded-2xl shadow-sm border border-gray-100 p-16 text-center">
                        <div className="w-20 h-20 bg-gray-100 rounded-full flex items-center justify-center mx-auto mb-5">
                            <svg className="w-10 h-10 text-gray-300" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M19 7l-.867 12.142A2 2 0 0116.138 21H7.862a2 2 0 01-1.995-1.858L5 7m5 4v6m4-6v6m1-10V4a1 1 0 00-1-1h-4a1 1 0 00-1 1v3M4 7h16" />
                            </svg>
                        </div>
                        <h3 className="text-lg font-semibold text-gray-700 mb-1">휴지통이 비어있습니다</h3>
                        <p className="text-sm text-gray-400">삭제한 문서가 없습니다</p>
                        <Link href="/" className="mt-6 inline-flex items-center gap-2 text-sm text-indigo-600 hover:text-indigo-700 font-medium">
                            ← 메인으로 돌아가기
                        </Link>
                    </div>
                )}

                {/* 문서 목록 */}
                {!isLoading && docs.length > 0 && (
                    <div className="space-y-3">
                        {docs.map((d) => {
                            const type = getTypeLabel(d);
                            const isBusy = actionId === d.id;
                            return (
                                <div key={d.id} className="bg-white rounded-xl shadow-sm border border-gray-100 px-5 py-4 flex items-center gap-4">
                                    {/* 타입 배지 */}
                                    <span className={`flex-shrink-0 px-2 py-0.5 text-[11px] font-bold rounded-lg border ${type.cls}`}>
                                        {type.label}
                                    </span>

                                    {/* 제목 + 메타 */}
                                    <div className="flex-1 min-w-0">
                                        <p className="font-semibold text-gray-900 truncate">{d.title || '(제목 없음)'}</p>
                                        <p className="text-xs text-gray-400 mt-0.5">
                                            삭제일: {formatDate(d.deletedAt)}
                                            {isAdmin && d.authorName && (
                                                <span className="ml-2 text-gray-300">| 작성자: {formatAuthorName(d.authorName)}</span>
                                            )}
                                        </p>
                                    </div>

                                    {/* 버튼 */}
                                    <div className="flex items-center gap-2 flex-shrink-0">
                                        <button
                                            onClick={() => handleRestore(d.id, d.title || '문서')}
                                            disabled={isBusy}
                                            className="px-3 py-1.5 text-xs font-semibold text-indigo-600 bg-indigo-50 hover:bg-indigo-100 rounded-lg transition-colors disabled:opacity-40"
                                        >
                                            {isBusy ? '처리 중...' : '복원'}
                                        </button>
                                        {(isAdmin || d.visibility === 'private' || d.docType === 'daily' || d.id.startsWith('daily-')) && (
                                            <button
                                                onClick={() => handlePurge(d.id, d.title || '문서')}
                                                disabled={isBusy}
                                                className="px-3 py-1.5 text-xs font-semibold text-red-600 bg-red-50 hover:bg-red-100 rounded-lg transition-colors disabled:opacity-40"
                                            >
                                                영구삭제
                                            </button>
                                        )}
                                    </div>
                                </div>
                            );
                        })}

                        <p className="text-center text-xs text-gray-400 pt-2">총 {docs.length}개의 삭제된 문서</p>
                    </div>
                )}
            </main>
        </div>
    );
}
