import { useEffect, useRef } from 'react';
import { renderAsync } from 'docx-preview';
import { useFileArrayBuffer } from '../../hooks/useFileBuffer';
import { FilePreviewFallback } from './FilePreviewFallback';

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

export function DocxPreview({ fileId, fileName }: DocxPreviewProps) {
  const bodyRef = useRef<HTMLDivElement>(null);
  const styleRef = useRef<HTMLDivElement>(null);
  const { buffer, loading, error } = useFileArrayBuffer(fileId);

  useEffect(() => {
    const body = bodyRef.current;
    const style = styleRef.current;
    if (!buffer || !body || !style) return;

    body.innerHTML = '';
    style.innerHTML = '';

    let cancelled = false;
    renderAsync(buffer, body, style, {
      className: 'docx-preview',
      inWrapper: true,
      ignoreWidth: false,
      ignoreHeight: false,
      breakPages: true,
    }).catch(() => {
      if (!cancelled) {
        body.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 className="h-full w-full min-h-0 overflow-auto bg-white">
      <div ref={styleRef} className="docx-preview-styles" />
      <div
        ref={bodyRef}
        className="docx-preview-body p-4 [&_.docx-wrapper]:mx-auto [&_.docx-wrapper]:bg-white [&_.docx-wrapper]:shadow-sm"
      />
    </div>
  );
}
