import { useEffect, useRef } from 'react';
import { renderPptx } from 'pptx-react-renderer';
import { useFileArrayBuffer } from '../../hooks/useFileBuffer';
import { FilePreviewFallback } from './FilePreviewFallback';

interface PptxPreviewProps {
  fileId: string;
  fileName: string;
}

export function PptxPreview({ fileId, fileName }: PptxPreviewProps) {
  const containerRef = useRef<HTMLDivElement>(null);
  const { buffer, loading, error } = useFileArrayBuffer(fileId);

  useEffect(() => {
    const container = containerRef.current;
    if (!buffer || !container) return;

    container.innerHTML = '';
    let cancelled = false;

    renderPptx(buffer, {
      container,
      scale: 0.55,
      showSlideNumbers: true,
      theme: 'light',
    }).catch(() => {
      if (!cancelled) container.innerHTML = '';
    });

    return () => {
      cancelled = true;
    };
  }, [buffer, fileId]);

  if (error || (!loading && !buffer)) {
    return <FilePreviewFallback fileId={fileId} fileName={fileName} error={error} />;
  }

  if (loading) {
    return <FilePreviewFallback fileId={fileId} fileName={fileName} loading />;
  }

  return (
    <div
      ref={containerRef}
      className="h-full w-full min-h-0 overflow-auto bg-slate-100 p-4 [&_.pptx-slide]:mx-auto [&_.pptx-slide]:mb-6"
    />
  );
}
