import styled from "styled-components";
import EarIcon from "../icons/ears";
import SpeakerIcon from "../icons/speaker";
import classNames from "classnames";
import { useEffect, useState } from "react";
import { useSpeechSynthesis } from "react-speech-kit";
import useAudioPlayer from "../../../useAudioPlayer";
import AudioWaveComponent from "../../../useAudioPlayer/audioWave";
import useTranslation from "../../../../hooks/useTranslation.jsx";
import wordStore from "../../../../mc/wordStore.json";
const PlayButton = ({
  type,
  refernceText,
  audio,
  notPlay,
  onPlaying,
  isStudent,
}) => {
  const { findText } = useTranslation(wordStore);
  const [isPlayingSpeak, setIsPlayingSpeak] = useState(false);
  const { speak, cancel } = useSpeechSynthesis({
    onEnd: () => {
      setIsPlayingSpeak(false);
      if (type === "ai") onPlaying?.(false);
    },
  });

  // Resolve fileId from audio object for URL resolution
  const resolvedFileId = audio?.id || audio?.file_id;
  const useFileIdResolution = !!resolvedFileId;

  const { play, isPlaying, isReady, stop } = useAudioPlayer({
    streamSrc: useFileIdResolution ? undefined : audio?.url,
    src: useFileIdResolution ? undefined : audio?.uploaded_media_url,
    fileId: resolvedFileId,
  });
  const showWave = isPlaying || isPlayingSpeak;
  const disabled = type !== "ai" && !isReady;
  useEffect(() => {
    return () => {
      if (showWave) {
        cancel();
        stop();
        onPlaying?.(false);
      }
    };
  }, [showWave]);
  useEffect(() => {
    if (type !== "ai") {
      onPlaying?.(isPlaying);
    } else {
      onPlaying?.(isPlayingSpeak);
    }
  }, [isPlaying, type, isPlayingSpeak]);
  return (
    <Container
      disabled={disabled}
      style={
        notPlay
          ? {
              cursor: "not-allowed",
            }
          : undefined
      }
      className={classNames({
        "ai-mode": type === "ai",
      })}
      onClick={() => {
        if (notPlay) return;
        if (type === "ai" && refernceText) {
          if (isPlayingSpeak) {
            setIsPlayingSpeak(false);
            cancel();
          } else {
            setIsPlayingSpeak(true);
            speak({
              text: refernceText,
            });
          }
        } else {
          if (audio) {
            if (isPlaying) {
              stop();
            } else {
              play();
            }
          }
        }
      }}
    >
      {showWave ? (
        <AudioWaveComponent
          playState={"play"}
          type="extra-small"
          count={16}
          color={type == "ai" ? "#00C2C2" : undefined}
        />
      ) : (
        <p>
          {type === "ai"
            ? findText("Correct response")
            : isStudent
            ? findText("You said")
            : findText("Student's response")}
        </p>
      )}

      {type === "ai" ? <EarIcon /> : <SpeakerIcon />}
    </Container>
  );
};
export default PlayButton;
const Container = styled.button`
  width: 100%;
  display: flex;
  align-items: center;
  height: 44px;
  padding: 0 12px;
  border-radius: 32px;
  background: #fff9e8;
  border: none;
  outline: none;
  cursor: pointer;
  justify-content: space-between;

  p {
    flex: 1;
    text-align: left;
    color: #636666;
    font-size: 14px;
    white-space: nowrap;
  }
  &.ai-mode {
    background: #00c2c21a;
  }
  &:disabled {
    opacity: 0.5;
    cursor: not-allowed;
  }
`;
