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

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

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

interface AudioPlayerProps {
  src: string;
}

const AudioPlayer: React.FC<AudioPlayerProps> = ({ src }) => {

  const audioRef = useRef<HTMLAudioElement>(null);
  const [isPlaying, setIsPlaying] = useState(false);
  const [progress, setProgress] = useState(0);

  // Обновление прогресса воспроизведения
  useEffect(() => {
    const audio = audioRef.current;
    if (!audio) return;

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

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

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

  // Воспроизведение или пауза
  const togglePlay = () => {
    const audio = audioRef.current;
    if (!audio) return;

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

  // Обработка изменения прогресса
  const handleProgressClick = (
    e: React.MouseEvent<HTMLDivElement, MouseEvent>
  ) => {
    const audio = audioRef.current;
    if (!audio) return;

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



  return (
    <div className='flex items-center gap-2'>
      <audio ref={audioRef} 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 AudioPlayer;
