'use client';

import { useState, useEffect } from 'react';
import { collection, query, where, getDocs, orderBy, doc, updateDoc } from 'firebase/firestore';
import { db } from '@/lib/firebase';

interface ArchivedDocument {
  id: string;
  title: string;
  category: string;
  updatedAt: string;
  question?: string;
  answer?: string;
}

export default function ArchivePage() {
  const [documents, setDocuments] = useState<ArchivedDocument[]>([]);
  const [loading, setLoading] = useState(true);
  const [expandedId, setExpandedId] = useState<string | null>(null);

  useEffect(() => {
    const load = async () => {
      setLoading(true);
      try {
        const q = query(
          collection(db, 'documents'),
          where('status', '==', 'rejected'),
          where('sourceType', 'in', ['kakao_expert', 'kakao_community', 'dashboard_insight']),
          orderBy('updatedAt', 'desc')
        );
        const snapshot = await getDocs(q);
        setDocuments(snapshot.docs.map(d => {
          const data = d.data();
          return {
            id: d.id,
            title: data.title || d.id,
            category: data.category || '',
            updatedAt: data.updatedAt?.toDate?.()?.toLocaleDateString('ko-KR') || '',
            question: data.question || '',
            answer: data.answer || '',
          };
        }));
      } catch (err) {
        console.error('Failed to load archived documents:', err);
      } finally {
        setLoading(false);
      }
    };
    load();
  }, []);

  const handleRestore = async (docId: string) => {
    if (!confirm('이 문서를 검토 대기 상태로 복원하시겠습니까?')) return;
    try {
      await updateDoc(doc(db, 'documents', docId), {
        status: 'pending',
        visibility: 'private',
      });
      setDocuments(prev => prev.filter(d => d.id !== docId));
      alert('복원 완료 — 검토 대기열에 다시 표시됩니다');
    } catch (err) {
      alert('복원 실패');
    }
  };

  return (
    <div className="min-h-screen bg-gray-50 p-6">
      <h1 className="text-2xl font-bold text-gray-900 mb-2">아카이브 (반려 문서)</h1>
      <p className="text-sm text-gray-500 mb-6">반려 처리된 문서 목록입니다. 필요 시 검토 대기 상태로 복원할 수 있습니다.</p>

      {loading ? (
        <div className="text-center py-16 text-gray-400">로딩 중...</div>
      ) : documents.length === 0 ? (
        <div className="text-center py-16 bg-white rounded-xl border border-gray-200">
          <p className="text-gray-500 font-medium">반려된 문서가 없습니다</p>
        </div>
      ) : (
        <div className="space-y-3">
          {documents.map(d => (
            <div key={d.id} className="bg-white rounded-xl border border-gray-200 px-5 py-4">
              <div
                className="cursor-pointer flex items-center justify-between"
                onClick={() => setExpandedId(expandedId === d.id ? null : d.id)}
              >
                <div>
                  <p className="font-bold text-gray-900">{d.title}</p>
                  <p className="text-xs text-gray-400 mt-1">
                    {d.category && <span>{d.category} · </span>}
                    {d.updatedAt}
                  </p>
                </div>
                <div className="flex items-center gap-2">
                  <span className="px-2 py-0.5 rounded-full text-xs font-bold bg-red-100 text-red-700">반려</span>
                  <button
                    onClick={(e) => { e.stopPropagation(); handleRestore(d.id); }}
                    className="px-3 py-1.5 bg-blue-100 text-blue-700 text-xs font-bold rounded-lg hover:bg-blue-200"
                  >
                    복원
                  </button>
                </div>
              </div>
              {expandedId === d.id && (
                <div className="mt-3 pt-3 border-t border-gray-100">
                  {d.question && (
                    <div className="mb-2">
                      <p className="text-xs font-bold text-gray-500 mb-1">질문</p>
                      <p className="text-sm text-gray-700">{d.question}</p>
                    </div>
                  )}
                  {d.answer && (
                    <div>
                      <p className="text-xs font-bold text-gray-500 mb-1">답변</p>
                      <p className="text-sm text-gray-700 whitespace-pre-wrap">{d.answer}</p>
                    </div>
                  )}
                </div>
              )}
            </div>
          ))}
        </div>
      )}
    </div>
  );
}
