'use client';

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

import PauseButtonIcon from '@/svgs/PauseButtonIcon';
import PlayButtonIcon from '@/svgs/PlayButtonIcon/PlayButtonIcon';
import { formatTime } from '@/utils/formatTime';

import styles from './AudioPlayer.module.scss';

export default function AudioPlayer({ src = '' }: { src?: string }) {
  const audioRef = useRef<HTMLAudioElement | null>(null);

  const [duration, setDuration] = useState<number>(0);
  const [playing, setPlaying] = useState<boolean>(false);
  const [ready, setReady] = useState<boolean>(false);
  const [time, setTime] = useState<number>(0);

  const onTogglePlayPause = () => {
    if (playing) {
      audioRef.current?.pause();
    } else {
      audioRef.current?.play();
    }

    setPlaying((playing) => !playing);
  };

  useEffect(() => {
    if (!!audioRef?.current?.duration) {
      setDuration(audioRef.current.duration);
    }
  }, [ready]);

  const formattedTime = useMemo(() => {
    if (playing) {
      return formatTime(time || 0);
    }

    return formatTime(time || duration || 0);
  }, [duration, playing, time]);

  return !!src?.length && (
    <div className={styles.AudioPlayer}>
      <audio
        ref={audioRef}
        preload="metadata"
        onCanPlay={() => setReady(true) }
        onPause={() => setPlaying(false)}
        onPlaying={() => setPlaying(true)}
        onTimeUpdate={(event) => setTime(event?.currentTarget?.currentTime || 0) }
      >
        <source
          src={src}
          type={`audio/${src?.includes('wav') ? 'wav' : 'mpeg'}`}
        />
      </audio>
      <div className={styles['progress-bar']}>
        <div
          className={styles.progress}
          style={{ width: `${(time / (duration || 1) * 100)}%` }}
        />
      </div>
      <button
        className={styles['play-pause']}
        type="button"
        onClick={onTogglePlayPause}
      >
        {playing ? <PauseButtonIcon/> : <PlayButtonIcon />}
      </button>
      <p className={styles.time}>{formattedTime}</p>
    </div>
  );
};
