import React, { useEffect, useMemo, useState } from 'react';
import type { DocumentRecord } from '../types/documents.types';
import { documentsApi } from '../api/documents.api';
import { GestureImageViewer } from './GestureImageViewer';

interface Props {
  doc: DocumentRecord;
}

export const DocumentPreview: React.FC<Props> = ({ doc }) => {
  const [blobUrl, setBlobUrl] = useState<string | null>(null);
  const [error, setError] = useState<string | null>(null);

  const previewable = useMemo(() => {
    return doc.contentType === 'application/pdf' || doc.contentType?.startsWith('image/');
  }, [doc.contentType]);

  useEffect(() => {
    let revoked: string | null = null;
    (async () => {
      try {
        if (!previewable) return;
        const data = await documentsApi.download(doc.id);
        const url = URL.createObjectURL(data);
        setBlobUrl(url);
        revoked = url;
      } catch (e) {
        setError('Failed to load preview');
      }
    })();
    return () => {
      if (revoked) URL.revokeObjectURL(revoked);
    };
  }, [doc.id, previewable]);

  if (!previewable) return <div className="text-slate-500 text-sm">No preview available.</div>;
  if (error) return <div className="text-red-600 text-sm">{error}</div>;
  if (!blobUrl) return <div className="text-slate-500 text-sm">Loading preview...</div>;

  if (doc.contentType === 'application/pdf') {
    return (
      <object data={blobUrl} type="application/pdf" className="w-full h-[60vh] rounded-lg border" aria-label="PDF Preview">
        <a href={blobUrl} target="_blank" rel="noopener noreferrer">Open PDF</a>
      </object>
    );
  }

  return (
    <div className="rounded-lg border overflow-hidden bg-gray-50">
      <GestureImageViewer
        src={blobUrl}
        alt={doc.title}
        className="max-w-full h-auto min-h-[300px] max-h-[80vh]"
      />
    </div>
  );
};

export default DocumentPreview;

