import React, {createContext, ReactNode, useReducer, useState} from 'react'
import {SdkStateGlobalBase} from '@/types/SdkStateGlobalBase'
import publisherAudioReducer from './reducers/publisherAudioReducer'
import publisherVideosReducer from './reducers/publisherVideosReducer'
import attendeesReducer from './reducers/attendeesReducer'
import participantsReducer from './reducers/participantsReducer'

export interface SdkStateGlobalContextValue extends SdkStateGlobalBase {}

export const SdkStateGlobalContext = createContext<SdkStateGlobalBase | undefined>(undefined)

export interface SdkStateGlobalContextProps {
  initialProps: SdkStateGlobalBase
  children?: ReactNode
}

export function SdkStateGlobalContextProvider(props: SdkStateGlobalContextProps): JSX.Element {
  const { initialProps } = props
  const [ stateAll, setStateAll ] = useState(initialProps.stateAll)
  const [ cameraList, setCameraList ] = useState(initialProps.cameraList)
  const [ currentCamera, setCurrentCamera ] = useState(initialProps.currentCamera)
  const [ participants, setParticipants ] = useReducer(participantsReducer, initialProps.participants)
  const [ attendees, setAttendees ] = useReducer(attendeesReducer, initialProps.attendees)
  const [ publisherVideos, setPublisherVideos ] = useReducer(publisherVideosReducer, initialProps.publisherVideos)
  const [ publisherAudios, setPublisherAudios ] = useReducer(publisherAudioReducer, initialProps.publisherVideos)

  const value: SdkStateGlobalBase = {
    stateAll: stateAll,
    setStateAll: setStateAll,
    cameraList: cameraList,
    setCameraList: setCameraList,
    currentCamera: currentCamera,
    setCurrentCamera: setCurrentCamera,
    participants: participants,
    setParticipants: setParticipants,
    attendees: attendees,
    setAttendees: setAttendees,
    publisherVideos: publisherVideos,
    setPublisherVideos: setPublisherVideos,
    publisherAudios: publisherAudios,
    setPublisherAudios: setPublisherAudios,
  }

  return (
    <SdkStateGlobalContext.Provider value={value}>
      {props.children}
    </SdkStateGlobalContext.Provider>
  )
}
