import { useEffect, useState } from 'react';
import LoadingWheel from './LoadingWheel';
import FileBox from './FileBox';

// Cache to keep track of loaded media
const loadedMedia = new Set();

const AttachmentPreview = ({ url }: { url: string }) => {
  const isImage = url.match(/\.(jpg|jpeg|png|gif|bmp|webp)$/i);
  const isVideo = url.match(/\.(mp4|webm|ogg|mov)$/i);
  const [isLoading, setIsLoading] = useState(!loadedMedia.has(url));

  useEffect(() => {
    if (isImage && !loadedMedia.has(url)) {
      // Preload image
      const img = new Image();
      img.onload = () => {
        loadedMedia.add(url);
        setIsLoading(false);
      };
      img.src = url;
    } else if (isVideo && !loadedMedia.has(url)) {
      // Preload video metadata
      const video = document.createElement('video');
      video.onloadedmetadata = () => {
        loadedMedia.add(url);
        setIsLoading(false);
      };
      video.src = url;
    }
  }, [url, isImage, isVideo]);

  if (!isImage && !isVideo) {
    return <FileBox url={url} />;
  }

  if (isVideo) {
    return (
      <div className="relative min-h-64 w-full">
        {isLoading && (
          <div className="absolute inset-0 flex items-center justify-center bg-gray-800 bg-opacity-50 rounded">
            <LoadingWheel />
          </div>
        )}
        <video
          controls
          className={`max-w-full max-h-64 w-full rounded transition-opacity duration-200 ${
            isLoading ? 'opacity-0' : 'opacity-100'
          }`}
          onLoadedMetadata={() => setIsLoading(false)}
        >
          <source src={url} type={`video/${url.split('.').pop()}`} />
          Your browser does not support the video tag.
        </video>
      </div>
    );
  }

  return (
    <div className="relative min-h-64 w-full ">
      {isLoading && (
        <div className="absolute inset-0 flex items-center justify-center bg-gray-800 bg-opacity-50 rounded">
          <LoadingWheel />
        </div>
      )}
      <a href={url} target="_blank" rel="noopener noreferrer">
        <img
          src={url}
          alt="attachment"
          className={`max-w-full max-h-64 object-contain rounded transition-opacity duration-200 ${
            isLoading ? 'opacity-0' : 'opacity-100'
          }`}
        />
      </a>
    </div>
  );
};

export default AttachmentPreview;
