import { createContext, FC, useCallback, useContext, useState } from 'react';

export type AudioManagerContextValue = {
  audioToPlay: string;
  setNextAudioToPlay: (audio: string) => void;
  audioPlaying: AudioPlayingType;
  setAudioPlaying: (audio: AudioPlayingType) => void;
};

const AudioManagerContext = createContext<AudioManagerContextValue>({
  audioToPlay: '',
  setNextAudioToPlay: () => null,
  audioPlaying: {
    messageTs: null,
    isPlaying: false,
  },
  setAudioPlaying: () => null,
});

export type AudioManagerProps = {};

export type AudioPlayingType = {
  messageTs: string | null;
  isPlaying: boolean;
};

export const AudioManagerProvider: FC<
  React.PropsWithChildren<AudioManagerProps>
> = props => {
  const { children } = props;

  const [audioToPlay, setAudioToPlay] = useState('');
  const [audioPlaying, setAudioPlaying] = useState<AudioPlayingType>({
    messageTs: null,
    isPlaying: false,
  });

  const setNextAudioToPlay = useCallback((audio: string) => {
    setAudioToPlay(audio);
  }, []);

  const setAudioPlayingCallback = useCallback((audio: AudioPlayingType) => {
    setAudioPlaying(audio);
  }, []);

  return (
    <AudioManagerContext.Provider
      value={{
        audioToPlay,
        setNextAudioToPlay,
        audioPlaying,
        setAudioPlaying: setAudioPlayingCallback,
      }}
    >
      {children}
    </AudioManagerContext.Provider>
  );
};

export const useAudioManager = () => useContext(AudioManagerContext);

export const AudioManagerConsumer = AudioManagerContext.Consumer;

export default AudioManagerContext;
