import { useRef, useState, useEffect, useCallback } from "react";
import { StaticImageData } from "next/image";
import VideoPlayerIcon from "../icons/VideoPlayerIcon";
import { FaVolumeUp, FaVolumeMute } from "react-icons/fa";
import { IoPause } from "react-icons/io5";

type VideoComponentProps = {
  videoSrc?: string;
  posterSrc: string | StaticImageData;
};

export default function VideoComponent({
  videoSrc,
  posterSrc,
}: VideoComponentProps) {
  const videoRef = useRef<HTMLVideoElement | null>(null);
  const [isPlaying, setIsPlaying] = useState(false);
  const [progress, setProgress] = useState(0);
  const [volume, setVolume] = useState(1); // Default volume is 1 (100%)
  const [isControlsVisible, setIsControlsVisible] = useState(false);
  const [isMuted, setIsMuted] = useState(false);
  const [hideTimeout, setHideTimeout] = useState<NodeJS.Timeout | null>(null);

  const handlePlayPause = () => {
    if (videoRef.current) {
      if (isPlaying) {
        videoRef.current.pause();
      } else {
        videoRef.current.play();
      }
      setIsPlaying(!isPlaying);
    }
  };

  const handleStop = () => {
    if (videoRef.current) {
      if (isPlaying) {
        videoRef.current.pause();
        setIsPlaying(false);
      }
    }
  };

  const handleProgressChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    if (videoRef.current) {
      const value = parseFloat(e.target.value);
      videoRef.current.currentTime = (value / 100) * videoRef.current.duration;
      setProgress(value);
    }
  };

  const handleVolumeChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    if (videoRef.current) {
      const value = parseFloat(e.target.value);
      videoRef.current.volume = value;
      setVolume(value);
    }
  };

  const toggleMute = () => {
    if (videoRef.current) {
      videoRef.current.muted = !isMuted;
      setIsMuted(!isMuted);
    }
  };

  const showControls = useCallback(() => {
    setIsControlsVisible(true);
    if (hideTimeout) {
      clearTimeout(hideTimeout);
      setHideTimeout(null);
    }
  }, [hideTimeout]);

  const hideControls = useCallback(() => {
    const timeout = setTimeout(() => {
      setIsControlsVisible(false);
    }, 2000);
    setHideTimeout(timeout);
  }, []);

  useEffect(() => {
    const video = videoRef.current;

    if (video) {
      const updateProgress = () => {
        if (video) {
          const percentage = (video.currentTime / video.duration) * 100;
          setProgress(percentage);
        }
      };

      const interval = setInterval(updateProgress, 500); // Update progress every 500ms
      video.addEventListener("play", showControls);
      video.addEventListener("pause", hideControls);
      video.addEventListener("ended", hideControls);

      return () => {
        clearInterval(interval);
        video.removeEventListener("play", showControls);
        video.removeEventListener("pause", hideControls);
        video.removeEventListener("ended", hideControls);
        if (hideTimeout) clearTimeout(hideTimeout);
      };
    }
  }, [isPlaying, showControls, hideControls, hideTimeout]);

  const posterUrl = typeof posterSrc === "string" ? posterSrc : posterSrc.src;

  return (
    <div
      className="relative w-full pb-[56.25%] cursor-pointer overflow-hidden rounded-xl  shadow-2xl"
      onMouseEnter={showControls}
      onMouseLeave={hideControls}
    >
      <video
        ref={videoRef}
        className="w-full h-full object-cover absolute top-0 left-0"
        src={videoSrc}
        poster={posterUrl}
        onClick={handlePlayPause}
      />
      {!isPlaying && (
        <button
          onClick={handlePlayPause}
          className="absolute top-1/2 left-1/2 transform -translate-x-1/2 -translate-y-1/2 bg-transparent border-none cursor-pointer"
        >
          <VideoPlayerIcon />
        </button>
      )}
      {isPlaying && isControlsVisible && (
        <div className="absolute bottom-0 left-0 right-0 p-2 bg-gray-800 bg-opacity-75 rounded-b-xl flex items-center gap-2" style={{overflow: 'hidden'}}>
          <button
            onClick={handleStop}
            className="text-white p-1 rounded-full hover:bg-gray-600"
          >
            <IoPause />
          </button>
          <input
            type="range"
            min="0"
            max="100"
            value={progress}
            className="flex-1 cursor-pointer"
            onChange={handleProgressChange}
            style={{overflow: 'hidden'}}
          />
          <div className="flex items-center gap-2">
            <button
              onClick={toggleMute}
              className="text-white p-1 rounded-full hover:bg-gray-600"
            >
              {isMuted ? <FaVolumeMute /> : <FaVolumeUp />}
            </button>
            <input
              type="range"
              min="0"
              max="1"
              step="0.01"
              value={volume}
              className="w-9 lg:w-24 cursor-pointer"
              onChange={handleVolumeChange}
              style={{overflow: 'hidden'}} // Ensure volume control stays within bounds
            />
          </div>
        </div>
      )}
    </div>
  );
}
