import React from "react";

function VideoPlayer({ url, con }) {
  const getVideoData = (url) => {
    const youtubeRegex = /(?:https?:\/\/)?(?:www\.)?(?:youtube\.com\/(?:[^\/\n\s]+\/\S+\/|(?:v|e(?:mbed)?)\/|\S*?[?&]v=)|youtu\.be\/)([a-zA-Z0-9_-]{11})/;
    const googleDriveRegex = /https?:\/\/drive\.google\.com\/file\/d\/([a-zA-Z0-9_-]+)\/(?:view|preview)/;

    if (youtubeRegex.test(url)) {
      const videoId = url.match(youtubeRegex)[1];
      return {
        source: "YouTube",
        embedUrl: `https://www.youtube.com/embed/${videoId}`,
        thumbnailUrl: `https://img.youtube.com/vi/${videoId}/hqdefault.jpg`, 
      };
    } else if (googleDriveRegex.test(url)) {
      const fileId = url.match(googleDriveRegex)[1];
      return {
        source: "Google Drive",
        embedUrl: `https://drive.google.com/file/d/${fileId}/preview`,
        // thumbnailUrl: `https://drive.google.com/thumbnail?id=${fileId}`,
        thumbnailUrl: `https://lh3.googleusercontent.com/d/${fileId}=s220?authuser=0`
      };
    } else {
      return { source: "Unknown", embedUrl: null, thumbnailUrl: null };
    }
  };

  const videoData = getVideoData(url);

  if (videoData.source === "Unknown") {
    return <p className="text-red">invalid URL.</p>;
  }


  return (
    con === 'main'?(
      <div className="me-2" 
        style={{
          aspectRatio:"3/2",
          width:"10vw",
          position: "relative", 
          display: "flex",
          justifyContent:"center",
          alignItems:"center",
          backgroundColor:"#000000",
          overflow:"hidden",
        }}
      >
        <img
          src={videoData.thumbnailUrl}
          alt={`${videoData.source} video thumbnail`}
          style={{ width: "100%", height:"100%", objectFit:"cover", display:"block", opacity:"0.6" }}
        />
        <div style={{
          position: "absolute",
          top: "50%",
          left: "50%",
          transform: "translate(-50%, -50%)",
        }}>
          {videoData.source === "YouTube" ? <i className="bi bi-youtube fs-1 text-white"></i> : <i className="bi bi-google fs-2 text-white"></i>}
        </div>
      </div>
    ):(
      <div style={{width:"30vw", height:"fit-content"}}>
        <iframe
          src={videoData.embedUrl}
          title={`${videoData.source} video player`}
          frameBorder="0"
          allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture"
          allowFullScreen
          style={{
            height:"auto"
          }}
          className="w-100 bg-secondary"
        ></iframe>
      </div>
    )
  );
}

export default VideoPlayer;