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

export type AudioContextValue = {
  setAudioPlaying: (messageId) => void;
  audioPlayingId: string | number | null;
  isPlaying: boolean;
};

const AudioContext = createContext<AudioContextValue>({
  setAudioPlaying: () => null,
  audioPlayingId: null,
  isPlaying: false,
});

export const AudioProvider: FC<React.PropsWithChildren<unknown>> = props => {
  const { children } = props;

  const [audioPlayingId, setAudioPlayingId] = useState(null);
  const [isPlaying, setIsPlaying] = useState(false);

  const setAudioPlaying = (audioId: number | null) => {
    setAudioPlayingId(audioId);
    setIsPlaying(audioId !== null);
  };

  return (
    <AudioContext.Provider
      value={{
        setAudioPlaying,
        audioPlayingId,
        isPlaying,
      }}
    >
      {children}
    </AudioContext.Provider>
  );
};

export const useAudio = () => useContext(AudioContext);

export const AudioConsumer = AudioContext.Consumer;

export default AudioContext;
