'use client';

import { useState, useEffect } from 'react';
import dynamic from 'next/dynamic';
import { collection, query, orderBy, getDocs, limit, Timestamp } from 'firebase/firestore';
import { db } from '@/lib/firebase';
import { COLLECTIONS } from '@/types/firestore';
import { formatAuthorName } from '@/lib/constants';
import { confirmDialog } from '@/lib/confirm';
import { useReviewPermission } from '@/hooks/useReviewPermission';

const VersionDiff = dynamic(() => import('@/components/review/VersionDiff'), { ssr: false });

interface Revision {
    id: string;
    title: string;
    content: string;
    authorName: string;
    createdAt: Timestamp;
    version: number;
    isRestored?: boolean; // 추가됨
}

interface RevisionHistoryModalProps {
    isOpen: boolean;
    onClose: () => void;
    docId: string;
    onRestore: (content: string, title: string) => void;
}

export default function RevisionHistoryModal({ isOpen, onClose, docId, onRestore }: RevisionHistoryModalProps) {
    const [revisions, setRevisions] = useState<Revision[]>([]);
    const [isLoading, setIsLoading] = useState(false);
    const [selectedRevisionIndex, setSelectedRevisionIndex] = useState<number | null>(null);
    const { canReview } = useReviewPermission();

    useEffect(() => {
        if (isOpen && docId) {
            fetchRevisions();
        }
    }, [isOpen, docId]);

    const fetchRevisions = async () => {
        setIsLoading(true);
        try {
            const revisionsRef = collection(db, COLLECTIONS.DOCUMENTS, docId, COLLECTIONS.REVISIONS);
            const q = query(revisionsRef, orderBy('createdAt', 'desc'), limit(20));
            const snapshot = await getDocs(q);

            const docs = snapshot.docs.map(doc => ({
                id: doc.id,
                ...doc.data()
            })) as Revision[];

            setRevisions(docs);
        } catch (error) {
            console.error("Error fetching revisions:", error);
        } finally {
            setIsLoading(false);
        }
    };

    if (!isOpen) return null;

    return (
        <div className="fixed inset-0 z-[110] flex items-center justify-center px-4" role="dialog" aria-modal="true">
            {/* Backdrop */}
            <div
                className="absolute inset-0 bg-slate-900/60 backdrop-blur-sm transition-opacity"
                onClick={onClose}
            />

            {/* Modal Content */}
            <div className="relative w-full max-w-2xl bg-white rounded-3xl shadow-2xl overflow-hidden animate-in fade-in zoom-in-95 duration-200">
                <div className="px-6 py-5 border-b border-gray-100 bg-slate-50 flex items-center justify-between">
                    <div>
                        <h3 className="text-xl font-bold text-slate-900">변경 이력 (History)</h3>
                        <p className="text-xs text-slate-500 mt-1">최근 20개의 수정 내역을 확인할 수 있습니다.</p>
                    </div>
                    <button
                        onClick={onClose}
                        className="p-2 hover:bg-white rounded-full transition-colors text-slate-400 hover:text-slate-600 shadow-sm border border-transparent hover:border-slate-200"
                    >
                        <svg className="w-5 h-5" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                            <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M6 18L18 6M6 6l18 18" />
                        </svg>
                    </button>
                </div>

                <div className="max-h-[60vh] overflow-y-auto p-4 bg-white">
                    {isLoading ? (
                        <div className="py-20 text-center">
                            <div className="inline-block w-8 h-8 border-3 border-amber-500 border-t-transparent rounded-full animate-spin"></div>
                            <p className="mt-4 text-sm text-slate-500 font-medium">이력을 불러오는 중...</p>
                        </div>
                    ) : revisions.length === 0 ? (
                        <div className="py-20 text-center">
                            <div className="w-16 h-16 bg-slate-50 rounded-full flex items-center justify-center mx-auto mb-4">
                                <svg className="w-8 h-8 text-slate-300" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                    <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M12 8v4l3 3m6-3a9 9 0 11-18 0 9 9 0 0118 0z" />
                                </svg>
                            </div>
                            <p className="text-slate-500 font-medium text-lg">기록된 변경 이력이 없습니다.</p>
                            <p className="text-slate-400 text-sm mt-1">문서를 수정하면 여기에 이력이 남습니다.</p>
                        </div>
                    ) : (
                        <div className="space-y-3">
                            {revisions.map((rev, index) => (
                                <div
                                    key={rev.id}
                                    className={`p-4 rounded-2xl border transition-all duration-200 ${index === 0 ? 'bg-amber-50/30 border-amber-100' : 'bg-white border-slate-100 hover:border-slate-200 hover:shadow-sm'}`}
                                >
                                    <div className="flex items-start justify-between">
                                        <div className="flex-1">
                                            <div className="flex items-center gap-2 mb-1">
                                                <span className={`text-[10px] font-black px-2 py-0.5 rounded-full ${index === 0 ? 'bg-amber-100 text-amber-700' : 'bg-slate-100 text-slate-600'}`}>
                                                    {index === 0 ? '현재 버전' : `v${rev.version || '?'}`}
                                                </span>
                                                <span className="text-sm font-bold text-slate-900">
                                                    {rev.createdAt?.toDate().toLocaleString()}
                                                </span>
                                            </div>
                                            <div className="flex items-center gap-2 text-xs text-slate-500 font-medium">
                                                <div className="w-5 h-5 rounded-full bg-slate-200 flex items-center justify-center text-[8px] font-black text-slate-500">
                                                    {formatAuthorName(rev.authorName)?.[0] || 'A'}
                                                </div>
                                                <span>{formatAuthorName(rev.authorName)}</span>
                                                <span className="text-slate-300">|</span>
                                                <span className="truncate max-w-[200px]">{rev.title}</span>
                                                {rev.isRestored && (
                                                    <span className="ml-1 inline-flex items-center px-1.5 py-0.5 rounded text-[10px] font-bold bg-indigo-50 text-indigo-600 border border-indigo-100">
                                                        ♻️ 복구됨
                                                    </span>
                                                )}
                                            </div>
                                        </div>
                                        <div className="flex items-center gap-2 shrink-0">
                                            {canReview && index < revisions.length - 1 && (
                                                <button
                                                    onClick={() => setSelectedRevisionIndex(
                                                        selectedRevisionIndex === index ? null : index
                                                    )}
                                                    className={`px-3 py-1.5 rounded-xl text-xs font-bold transition-all shadow-sm active:scale-95 border ${
                                                        selectedRevisionIndex === index
                                                            ? 'bg-indigo-600 text-white border-indigo-600'
                                                            : 'bg-white border-indigo-200 text-indigo-600 hover:border-indigo-400'
                                                    }`}
                                                >
                                                    비교
                                                </button>
                                            )}
                                            {index > 0 && (
                                                <button
                                                    onClick={() => {
                                                        confirmDialog('이전 버전으로 복구하시겠습니까?\n(현재 작성 중인 최신 내용도 히스토리에 안전하게 백업되니 안심하고 복구하세요!)').then(ok => { if (ok) {
                                                            onRestore(rev.content, rev.title);
                                                            onClose();
                                                        }});
                                                    }}
                                                    className="px-3 py-1.5 bg-white border border-slate-200 text-slate-600 hover:text-amber-600 hover:border-amber-200 rounded-xl text-xs font-bold transition-all shadow-sm active:scale-95"
                                                >
                                                    이 버전으로 복원
                                                </button>
                                            )}
                                        </div>
                                    </div>
                                </div>
                            ))}
                        </div>
                    )}
                </div>

                {/* Version Diff Panel */}
                {selectedRevisionIndex !== null && revisions[selectedRevisionIndex] && revisions[selectedRevisionIndex + 1] && (
                    <div className="border-t border-gray-100 p-4">
                        <div className="flex items-center justify-between mb-3">
                            <div className="text-sm font-bold text-slate-700">
                                v{revisions[selectedRevisionIndex + 1].version || '?'} → v{revisions[selectedRevisionIndex].version || '?'} 비교
                            </div>
                            <button
                                onClick={() => setSelectedRevisionIndex(null)}
                                className="text-xs text-slate-500 hover:text-slate-700 font-medium px-2 py-1 rounded-lg hover:bg-slate-100 transition-colors"
                            >
                                비교 닫기
                            </button>
                        </div>
                        <VersionDiff
                            oldContent={revisions[selectedRevisionIndex + 1].content}
                            newContent={revisions[selectedRevisionIndex].content}
                            oldTitle={`v${revisions[selectedRevisionIndex + 1].version || '?'} (이전)`}
                            newTitle={`v${revisions[selectedRevisionIndex].version || '?'} (선택)`}
                        />
                    </div>
                )}

                <div className="p-4 bg-slate-50 border-t border-gray-100 text-center">
                    <p className="text-[11px] text-slate-400 font-medium leading-relaxed">
                        💡 5분 이내의 연속된 수정은 하나로 합쳐져 저장됩니다. (Squash 전략)<br />
                        복원을 실행하면 현재 문서 상태가 자동으로 아카이브됩니다.
                    </p>
                </div>
            </div>
        </div>
    );
}
