import React, { useEffect } from 'react';
import { Navigate, useNavigate, useParams } from 'react-router-dom';

import { useAppShell } from '../appShellContext';

const DocumentViewerRoute = () => {
  const {
    previewWorkspaceDocument,
    ensurePreviewData,
    notifyApiError,
  } = useAppShell();
  const { documentId } = useParams();
  const navigate = useNavigate();

  useEffect(() => {
    if (!documentId) {
      navigate('/documents', { replace: true });
      return;
    }

    let cancelled = false;

    const hydrate = async () => {
      try {
        await ensurePreviewData(documentId);
      } catch (error) {
        if (cancelled) {
          return;
        }
        notifyApiError(error, 'Failed to open document preview.');
        navigate('/documents', { replace: true });
      }
    };

    hydrate();

    return () => {
      cancelled = true;
    };
  }, [documentId, ensurePreviewData, notifyApiError, navigate]);

  if (!documentId) {
    return <Navigate to="/documents" replace />;
  }

  if (!previewWorkspaceDocument || previewWorkspaceDocument.id !== documentId) {
    return <div className="preview-workspace__message">Loading preview…</div>;
  }

  return <Navigate to="/documents" replace />;
};

export default DocumentViewerRoute;
