import React, { useRef, useState, useEffect } from "react";

interface AudioPlayerProps {
  urlAudio: string;
  fileName: string; // ✅ Tambahkan props ini
}

const AudioPlayer: React.FC<AudioPlayerProps> = ({ urlAudio, fileName }) => {
  const audioRef = useRef<HTMLAudioElement>(null);
  const [currentTime, setCurrentTime] = useState(0);

  const playAudio = () => {
    audioRef.current?.play();
  };

  const pauseAudio = () => {
    audioRef.current?.pause();
  };

  const stopAudio = () => {
    if (audioRef.current) {
      audioRef.current.pause();
      audioRef.current.currentTime = 0;
    }
  };

  useEffect(() => {
    const audio = audioRef.current;
    if (!audio) return;

    const updateTime = () => {
      setCurrentTime(audio.currentTime);
    };

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

  const formatTime = (time: number) => {
    const minutes = Math.floor(time / 60);
    const seconds = Math.floor(time % 60).toString().padStart(2, "0");
    return `${minutes}:${seconds}`;
  };

  return (
    <div className="mt-2">
      <h2 className="text-lg font-semibold">{fileName}</h2>
      <audio ref={audioRef} src={urlAudio} controls className="mt-1 w-full" />
      {/* <div className="mt-2 space-x-2">
        <button onClick={playAudio}>▶️ Play</button>
        <button onClick={pauseAudio}>⏸️ Pause</button>
        <button onClick={stopAudio}>⏹️ Stop</button>
      </div>
      <div className="mt-1 text-sm text-gray-500">{formatTime(currentTime)}</div> */}
    </div>
  );
};

export default AudioPlayer;
