import React from "react";

function VideoPlayer({ url }) {
  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",
        thumbnailUrl: `https://img.youtube.com/vi/${videoId}/hqdefault.jpg`, 
        videoLink: `https://www.youtube.com/watch?v=${videoId}`, 
      };
    } else if (googleDriveRegex.test(url)) {
      const fileId = url.match(googleDriveRegex)[1]; 
      return {
        source: "Google Drive",
        thumbnailUrl: `https://drive.google.com/thumbnail?id=${fileId}`,
        videoLink: `https://drive.google.com/file/d/${fileId}/view`,
      };
    } else {
      return { source: "Unknown", thumbnailUrl: null, videoLink: null };
    }
  };

  const videoData = getVideoData(url);

  if (videoData.source === "Unknown") {
    return <p>URL video tidak valid. Harap masukkan URL YouTube atau Google Drive yang benar.</p>;
  }

  return (
    <div className="video-thumbnail me-2" 
      style={{
        aspectRatio:"3/2",
        width:"10vw",
        position: "relative", 
        display: "flex",
        justifyContent:"center",
        alignItems:"center",
        backgroundColor:"#000000",
        overflow:"hidden",
      }}
    >
      <a href={videoData.videoLink} target="_blank" rel="noopener noreferrer">
        <img
          src={videoData.thumbnailUrl}
          alt={`${videoData.source} video thumbnail`}
          style={{ width: "100%", height:"auto", 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>
      </a>
    </div>
  );
}

export default VideoPlayer;
