'use client';

import { useDocumentReviewListener } from '@/hooks/useDocumentReviewListener';
import type { Review } from '@/types/firestore';

interface ReviewTimelineProps {
  docId: string;
  isOpen: boolean;
  onClose: () => void;
}

function DecisionBadge({ decision }: { decision: Review['decision'] }) {
  const config = {
    approve: { label: '승인', className: 'bg-green-100 text-green-700 border-green-200' },
    reject: { label: '반려', className: 'bg-red-100 text-red-700 border-red-200' },
    revision_requested: { label: '수정요청', className: 'bg-amber-100 text-amber-700 border-amber-200' },
    request_revision: { label: '수정요청', className: 'bg-amber-100 text-amber-700 border-amber-200' },
  } as const;

  const fallback = { label: decision, className: 'bg-gray-100 text-gray-700 border-gray-200' };
  const c = (config as any)[decision] ?? fallback;

  return (
    <span className={`text-[10px] font-bold px-2 py-0.5 rounded-full border ${c.className}`}>
      {c.label}
    </span>
  );
}

export default function ReviewTimeline({ docId, isOpen, onClose }: ReviewTimelineProps) {
  const { reviews, loading } = useDocumentReviewListener(docId);

  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"
        onClick={onClose}
      />

      {/* Modal Content */}
      <div className="relative w-full max-w-lg bg-white rounded-3xl shadow-2xl overflow-hidden animate-in fade-in zoom-in-95 duration-200">
        {/* Header */}
        <div className="px-6 py-5 border-b border-gray-100 bg-slate-50 flex items-center justify-between">
          <h3 className="text-xl font-bold text-slate-900">검토 이력</h3>
          <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"
            aria-label="닫기"
          >
            <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 6l12 12" />
            </svg>
          </button>
        </div>

        {/* Body */}
        <div className="max-h-[60vh] overflow-y-auto p-6">
          {loading ? (
            <div className="py-16 flex flex-col items-center gap-3">
              <div className="w-8 h-8 border-3 border-indigo-500 border-t-transparent rounded-full animate-spin" />
              <p className="text-sm text-slate-500">불러오는 중...</p>
            </div>
          ) : reviews.length === 0 ? (
            <div className="py-16 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="M9 5H7a2 2 0 00-2 2v12a2 2 0 002 2h10a2 2 0 002-2V7a2 2 0 00-2-2h-2M9 5a2 2 0 002 2h2a2 2 0 002-2M9 5a2 2 0 012-2h2a2 2 0 012 2" />
                </svg>
              </div>
              <p className="text-slate-500 font-medium">검토 이력이 없습니다</p>
            </div>
          ) : (
            <div className="relative">
              {/* 왼쪽 세로 라인 */}
              <div className="absolute left-3.5 top-2 bottom-2 border-l-2 border-slate-200" />

              <div className="space-y-6">
                {reviews.map((review) => (
                  <div key={review.id} className="relative flex gap-4">
                    {/* 원형 dot */}
                    <div className={`relative z-10 w-7 h-7 rounded-full border-2 flex items-center justify-center shrink-0 mt-1 ${
                      review.decision === 'approve'
                        ? 'bg-green-100 border-green-400'
                        : review.decision === 'reject'
                        ? 'bg-red-100 border-red-400'
                        : 'bg-amber-100 border-amber-400'
                    }`}>
                      {review.decision === 'approve' ? (
                        <svg className="w-3 h-3 text-green-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                          <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="3" d="M5 13l4 4L19 7" />
                        </svg>
                      ) : review.decision === 'reject' ? (
                        <svg className="w-3 h-3 text-red-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                          <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="3" d="M6 18L18 6M6 6l12 12" />
                        </svg>
                      ) : (
                        <svg className="w-3 h-3 text-amber-600" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                          <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="3" d="M12 9v4m0 4h.01" />
                        </svg>
                      )}
                    </div>

                    {/* 카드 */}
                    <div className="flex-1 bg-slate-50 rounded-2xl p-4 border border-slate-100">
                      <div className="flex items-center justify-between mb-2 flex-wrap gap-2">
                        <div className="flex items-center gap-2">
                          <span className="text-sm font-bold text-slate-800">{review.reviewerName}</span>
                          <DecisionBadge decision={review.decision} />
                        </div>
                        <span className="text-xs text-slate-400">{review.createdAt?.toDate?.().toLocaleString() ?? '-'}</span>
                      </div>

                      {review.comment && (
                        <p className="text-sm text-slate-600 leading-relaxed whitespace-pre-wrap">{review.comment}</p>
                      )}

                      {review.evidenceType && (
                        <div className="mt-2 inline-flex items-center gap-1 text-[11px] font-medium text-indigo-600 bg-indigo-50 px-2 py-0.5 rounded-full">
                          <span>근거 유형:</span>
                          <span>{review.evidenceType}</span>
                        </div>
                      )}

                      {review.sourceAttachments && review.sourceAttachments.length > 0 && (
                        <div className="mt-2 space-y-1">
                          {review.sourceAttachments.map((att, i) => (
                            <a
                              key={i}
                              href={att.url}
                              target="_blank"
                              rel="noopener noreferrer"
                              className="flex items-center gap-1 text-xs text-blue-600 hover:text-blue-800 hover:underline"
                            >
                              <svg className="w-3 h-3" fill="none" stroke="currentColor" viewBox="0 0 24 24">
                                <path strokeLinecap="round" strokeLinejoin="round" strokeWidth="2" d="M10 6H6a2 2 0 00-2 2v10a2 2 0 002 2h10a2 2 0 002-2v-4M14 4h6m0 0v6m0-6L10 14" />
                              </svg>
                              {att.label}
                            </a>
                          ))}
                        </div>
                      )}
                    </div>
                  </div>
                ))}
              </div>
            </div>
          )}
        </div>
      </div>
    </div>
  );
}
