import { useEffect, useRef, useState } from 'react';
import { renderExamPdfPages } from '../utils/renderExamPdf';

interface Props {
  title: string;
  bytes: Uint8Array | null;
  loading?: boolean;
  onClose: () => void;
}

export function ExamPaperPdfModal({ title, bytes, loading, onClose }: Props) {
  const containerRef = useRef<HTMLDivElement>(null);
  const [err, setErr] = useState('');

  useEffect(() => {
    if (!bytes || !containerRef.current) return;
    let cancelled = false;
    setErr('');
    renderExamPdfPages(containerRef.current, bytes).catch((e: unknown) => {
      if (!cancelled) {
        setErr(e instanceof Error ? e.message : 'Không hiển thị được PDF');
      }
    });
    return () => { cancelled = true; };
  }, [bytes]);

  return (
    <div className="modal-overlay exam-pdf-viewer-overlay" onClick={onClose}>
      <div className="exam-pdf-viewer-modal" onClick={(e) => e.stopPropagation()}>
        <div className="modal-header exam-pdf-viewer-header">
          <h2 className="modal-title">{title}</h2>
          <button type="button" className="modal-close-btn" onClick={onClose} aria-label="Đóng">×</button>
        </div>
        <div className="exam-pdf-viewer-scroll" ref={containerRef}>
          {loading && <p className="exam-pdf-viewer-status">Đang tải đề...</p>}
          {err && <p className="login-error" style={{ padding: '1rem' }}>{err}</p>}
          {!loading && !bytes && !err && (
            <p className="exam-pdf-viewer-status">Không có dữ liệu PDF</p>
          )}
        </div>
      </div>
    </div>
  );
}
