import React, { useMemo, useEffect } from 'react';
import { blobFromAudioBuffer } from '../utils/utils';

interface AudioPlayerProps {
  audioBuffer: AudioBuffer;
  filename?: string; // Optional filename prop
}

export const AudioPlayer: React.FC<AudioPlayerProps> = ({ audioBuffer, filename = 'podcast.wav' }) => {
  // Create a Blob URL from the audioBuffer.
  const blobUrl = useMemo(() => {
    const wavBlob = blobFromAudioBuffer(audioBuffer);
    return URL.createObjectURL(wavBlob);
  }, [audioBuffer]);


  // Clean up the object URL when the component unmounts or audioBuffer changes.
  useEffect(() => {
    return () => {
      URL.revokeObjectURL(blobUrl);
    };
  }, [blobUrl]);

  return (
    <div className="mt-4 flex items-center">
      <audio controls src={blobUrl}>
        Your browser does not support the audio element.
      </audio>

      <a
        className="btn btn-sm btn-primary ml-2"
        href={blobUrl} // Use the same blobUrl for download
        download={filename}
      >
        Download
      </a>
    </div>
  );
};