import React, { useEffect, useRef, useState } from 'react';
import { axiosInstance } from '../../../services/axios';

interface DocxThumbnailProps {
  url: string;
  fallback: React.ReactNode;
}

export const DocxThumbnail: React.FC<DocxThumbnailProps> = ({ url, fallback }) => {
  const containerRef = useRef<HTMLDivElement>(null);
  const parentRef = useRef<HTMLDivElement>(null);
  const [scale, setScale] = useState(0.2);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState(false);

  useEffect(() => {
    let isMounted = true;
    
    axiosInstance.get(url, { responseType: 'arraybuffer' })
      .then(async (res) => {
        if (!isMounted) return;
        try {
          const { renderAsync } = await import('docx-preview');
          if (containerRef.current) {
            containerRef.current.innerHTML = '';
            await renderAsync(res.data, containerRef.current);
            setLoading(false);
          }
        } catch (err) {
          console.error('[DocxThumbnail] Render error:', err);
          setError(true);
          setLoading(false);
        }
      })
      .catch(err => {
        console.error('[DocxThumbnail] Fetch error:', err);
        if (isMounted) {
          setError(true);
          setLoading(false);
        }
      });

    return () => {
      isMounted = false;
    };
  }, [url]);

  useEffect(() => {
    if (!parentRef.current) return;
    const updateScale = () => {
      if (parentRef.current) {
        const width = parentRef.current.offsetWidth || 280;
        setScale(width / 800);
      }
    };
    updateScale();
    const observer = new ResizeObserver(updateScale);
    observer.observe(parentRef.current);
    return () => observer.disconnect();
  }, []);

  if (error) return <>{fallback}</>;

  return (
    <div ref={parentRef} className="w-full h-full relative overflow-hidden bg-white select-none pointer-events-none">
      {loading && (
        <div className="absolute inset-0 flex items-center justify-center bg-slate-50 z-10">
          <div className="w-5 h-5 rounded-full border-2 border-indigo-600 border-t-transparent animate-spin" />
        </div>
      )}
      <div 
        ref={containerRef}
        className="absolute top-0 left-0 origin-top-left"
        style={{
          width: '800px',
          height: '1000px',
          transform: `scale(${scale})`,
          padding: '16px',
          overflow: 'hidden',
        }}
      />
    </div>
  );
};
