import { useState, useRef, useCallback, useEffect } from 'react'
import { FaPlay, FaPause, FaExpand, FaBackward, FaForward, FaClosedCaptioning } from 'react-icons/fa'

interface VideoPlayerProps {
  src: string
  poster: string
  vttSrc: string
}

const VideoPlayer = ({ src, poster, vttSrc }: VideoPlayerProps) => {
  const [isPlaying, setIsPlaying] = useState(false)
  const [showControls, setShowControls] = useState(true)
  const [showCaptions, setShowCaptions] = useState(false)
  const [playbackRate, setPlaybackRate] = useState(1)
  const [progress, setProgress] = useState(0)
  const videoRef = useRef<HTMLVideoElement>(null)
  const timeoutRef = useRef<ReturnType<typeof setTimeout>>(null)
  
  const playbackRates = [0.5, 1, 2, 3]

  useEffect(() => {
    const video = videoRef.current
    if (!video) return

    const textTracks = video.textTracks[0]
    if (textTracks) {
      textTracks.mode = showCaptions ? 'showing' : 'hidden'
    }
  }, [showCaptions])

  const hideControlsWithDelay = useCallback(() => {
    if (timeoutRef.current) {
      clearTimeout(timeoutRef.current)
    }
    timeoutRef.current = setTimeout(() => {
      if (isPlaying) {
        setShowControls(false)
      }
    }, 3000)
  }, [isPlaying])

  const togglePlay = useCallback(() => {
    if (videoRef.current) {
      if (isPlaying) {
        videoRef.current.pause()
        setShowControls(true)
      } else {
        videoRef.current.play()
        hideControlsWithDelay()
      }
      setIsPlaying(!isPlaying)
    }
  }, [isPlaying, hideControlsWithDelay])

  const handleTimeSkip = (seconds: number) => {
    if (videoRef.current) {
      videoRef.current.currentTime += seconds
    }
  }

  const handleFullScreen = () => {
    if (videoRef.current) {
      videoRef.current.requestFullscreen()
    }
  }

  useEffect(() => {
    const video = videoRef.current
    if (!video) return

    const handleKeyPress = (e: KeyboardEvent) => {
      if (e.code === 'Space') {
        e.preventDefault()
        togglePlay()
      }
      if (e.code === 'ArrowLeft') {
        handleTimeSkip(-5)
      }
      if (e.code === 'ArrowRight') {
        handleTimeSkip(5)
      }
    }

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

    document.addEventListener('keydown', handleKeyPress)
    video.addEventListener('timeupdate', handleTimeUpdate)

    return () => {
      document.removeEventListener('keydown', handleKeyPress)
      video.removeEventListener('timeupdate', handleTimeUpdate)
    }
  }, [togglePlay])

  const handleMouseMove = () => {
    setShowControls(true)
    hideControlsWithDelay()
  }

  const handleProgressClick = (e: React.MouseEvent<HTMLDivElement>) => {
    const bounds = e.currentTarget.getBoundingClientRect()
    const x = e.clientX - bounds.left
    const percentage = (x / bounds.width) * 100
    if (videoRef.current) {
      videoRef.current.currentTime = (percentage / 100) * videoRef.current.duration
    }
  }

  return (
    <div 
      className="relative bg-black rounded-lg overflow-hidden"
      onMouseMove={handleMouseMove}
      onMouseLeave={() => isPlaying && setShowControls(false)}
    >
    <video
      ref={videoRef}
      poster={poster}
      controls={false}
      disablePictureInPicture
      className="w-full aspect-video cursor-pointer"
      onClick={togglePlay}
    >
        <source src={src} type="video/mp4" />
        <track
          src={vttSrc}
          kind="subtitles"
          srcLang="en"
          label="English"
        />
      </video>

      <div 
        className={`absolute bottom-0 left-0 right-0 transition-opacity duration-300 ${
          showControls ? 'opacity-100' : 'opacity-0'
        }`}
      >
        <div 
          className="absolute -top-4 left-0 right-0 h-8 cursor-pointer flex items-center"
          onClick={handleProgressClick}
        >
          <div className="w-full h-2 bg-gray-600">
            <div 
              className="h-full bg-[#4aa63f] transition-all duration-100"
              style={{ width: `${progress}%` }}
            />
          </div>
        </div>

        <div className="bg-gradient-to-t from-black/90 to-transparent p-4">
          <div className="flex items-center justify-between text-white">
            <div className="flex items-center space-x-4">
              <button 
                onClick={togglePlay} 
                className="bg-black text-white hover:text-accent-lake transition-colors p-2 rounded"
                aria-label={isPlaying ? 'Pause' : 'Play'}
              >
                {isPlaying ? 
                  <FaPause title="Pause" className="w-4 h-4" /> : 
                  <FaPlay title="Play" className="w-4 h-4" />
                }
              </button>
              <button 
                onClick={() => handleTimeSkip(-5)} 
                className="bg-black text-white hover:text-accent-lake transition-colors p-2 rounded"
                aria-label="Rewind 5 seconds"
              >
                <FaBackward title="Rewind" className="w-4 h-4" />
              </button>
              <button 
                onClick={() => handleTimeSkip(5)} 
                className="bg-black text-white hover:text-accent-lake transition-colors p-2 rounded"
                aria-label="Forward 5 seconds"
              >
                <FaForward title="Forward" className="w-4 h-4" />
              </button>
            </div>

            <div className="flex items-center space-x-4">
              <select
                value={playbackRate}
                onChange={(e) => {
                  setPlaybackRate(Number(e.target.value))
                  if (videoRef.current) {
                    videoRef.current.playbackRate = Number(e.target.value)
                  }
                }}
                className="bg-black text-white hover:text-accent-lake transition-colors p-2 rounded"
                aria-label="Playback Speed"
              >
                {playbackRates.map(rate => (
                  <option key={rate} value={rate} className="text-black">
                    {rate}x
                  </option>
                ))}
              </select>
              
              <button
                onClick={() => setShowCaptions(!showCaptions)}
                className={`bg-black p-2 rounded ${showCaptions ? 'text-[#4aa63f] hover:text-[#4aa63f]' : 'text-gray-600 hover:text-accent-lake'}`}
                aria-label="Toggle Captions"
              >
                <FaClosedCaptioning title="Captions" className="w-4 h-4" />
              </button>
              
              <button 
                onClick={handleFullScreen} 
                className="bg-black text-white hover:text-accent-lake transition-colors p-2 rounded"
                aria-label="Full Screen"
              >
                <FaExpand title="Full Screen" className="w-4 h-4" />
              </button>
            </div>
          </div>
        </div>
      </div>
    </div>
  )
}

export default VideoPlayer
