import {
  useEffect,
  useRef,
  useState,
} from 'react';

import {
  PauseIcon,
  PlayIcon,
} from 'lucide-react';

import { Button } from '@/components/ui/button';
import { Lang } from '@/lang/Lang';

interface VideoPlayerProps {
  src: string;
}

const VideoPlayer: React.FC<VideoPlayerProps> = ({ src }) => {
  const videoRef = useRef<HTMLVideoElement>(null);
  const [isPlaying, setIsPlaying] = useState(false);
  const [progress, setProgress] = useState(0);

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

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

    video.addEventListener('ended', () => {
      setIsPlaying(false);
      setProgress(0);
    });

    video.addEventListener('timeupdate', updateProgress);
    return () => {
      video.removeEventListener('timeupdate', updateProgress);
    };
  }, []);

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

    if (isPlaying) {
      video.pause();
    } else {
      video.play();
    }
    setIsPlaying(!isPlaying);
  };

  const handleProgressClick = (e: React.MouseEvent<HTMLDivElement, MouseEvent>) => {
    const video = videoRef.current;
    if (!video) return;

    const rect = (e.target as HTMLDivElement).getBoundingClientRect();
    const clickPosition = e.clientX - rect.left;
    const progressValue = clickPosition / rect.width;
    video.currentTime = video.duration * progressValue;
  };

  return (
    <div className='flex flex-col gap-2'>
      <div className='w-full flex justify-center'>
        <video className='w-[200px]' ref={videoRef} src={src} />
      </div>
      <div className='flex items-center gap-2'>
        <Button
          onClick={togglePlay}
          variant='ghost'
          size='icon'
          tooltip={Lang.key(isPlaying ? 'pause' : 'play')}
          aria-label={Lang.key(isPlaying ? 'pause' : 'play')}
        >
          {isPlaying ? <PauseIcon size={20} /> : <PlayIcon size={20} />}
        </Button>
        <div className='w-full bg-gray-200 rounded-full h-2' onClick={handleProgressClick}>
          <div className='bg-primary h-full rounded-full' style={{ width: `${progress}%` }} />
        </div>
      </div>
    </div>
  );
};

export default VideoPlayer;
