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

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

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

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

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

export default AudioPlayer;
