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

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

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

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 progress = clickPosition / rect.width;
    Video.currentTime = Video.duration * progress;
  };



  return (
    <div className='flex items-center gap-2'>
      <video ref={VideoRef} src={src} />
      <Button onClick={togglePlay} variant={'ghost'} size={'icon'} >
        {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>
  );
};



export default VideoPlayer;
