import React, { useEffect } from "react";

import { FaPause } from "react-icons/fa";
import {
  ResponseAudioBody,
  ResponseAudioContainer,
  ResponseAudioIcon,
  Line,
} from "./style/responseAutio.style";
import SpeakerIcon from "../../../../assets/svg/speakerIcon";
import AudioWaveComponent from "../../../useAudioPlayer/audioWave";
import useAudioPlayer from "../../../useAudioPlayer";
import PlayIcon from "../../../../assets/svg/playIcon";
import classNames from "classnames";

const ResponseAudio = ({ url, streamUrl, audioData, fileId }) => {
  // Resolve fileId: explicit prop takes priority, then fall back to audioData
  const resolvedFileId = fileId || audioData?.id || audioData?.file_id;
  
  // Use fileId mode when we have a fileId - let useAudioPlayer resolve the URL
  const useFileIdResolution = !!resolvedFileId;
  
  // When using fileId resolution, don't pass url/streamUrl to avoid conflicts
  const effectiveSrc = useFileIdResolution ? undefined : (audioData?.uploaded_media_url || url);
  const effectiveStreamSrc = useFileIdResolution ? undefined : (audioData?.url || streamUrl);
  
  const { play, isPlaying, isReady, pause } = useAudioPlayer({
    streamSrc: effectiveStreamSrc,
    src: effectiveSrc,
    fileId: resolvedFileId,
  });

  useEffect(() => {
    return () => {
      if (isPlaying) {
        stop();
      }
    };
  }, [isPlaying]);

  return (
    <ResponseAudioContainer
      className={classNames({
        disabled: !isReady,
      })}
    >
      <ResponseAudioBody>
        <SpeakerIcon />
        <Line />
        <AudioWaveComponent
          color="#fff"
          type="extra-small"
          count={11}
          playState={isPlaying ? "play" : "stop"}
        />
      </ResponseAudioBody>
      {isPlaying ? (
        <ResponseAudioIcon className="icon" onClick={pause}>
          <FaPause color="#febf10" size={16} />
        </ResponseAudioIcon>
      ) : (
        <ResponseAudioIcon className="icon" onClick={play}>
          <PlayIcon />
        </ResponseAudioIcon>
      )}
    </ResponseAudioContainer>
  );
};

export default ResponseAudio;
