import React from 'react'
import { JoinOptions } from '../../store'
import { getClassName, getMergedClassNames } from '../common'
import { useJoinPage } from './hooks'
import { JoinPageProps } from './models'
import { JoinPageHeader, JoinPageLocalStreams, JoinPageRoomButtons, JoinPageRoomInput } from './JoinPageComponents'
import zocksStyle from './JoinPage.module.scss'

export const JoinPage: React.FC<JoinPageProps> = ({
  joinAction,
  createRoomAction,
  initialRoomJoinInputValue = '',
  initialRoomJoinSelectValue = 'id',
  newMeetingDisabled = false,
  videoEnabledByDefault = false,
  audioEnabledByDefault = false,
  onNewRoomCreated,
  joinOptions = {},
  components = {},
  styles,
}) => {
  const { localMedia, afterJoinCleanUp } = useJoinPage(videoEnabledByDefault, audioEnabledByDefault)
  const { selectedAudioDeviceSettings, selectedVideoDeviceSettings, currentVirtualBackground } = localMedia

  const baseJoinOptions: Partial<JoinOptions> = {
    autoCreate: false,
    audioDeviceSettings: selectedAudioDeviceSettings,
    videoDeviceSettings: selectedVideoDeviceSettings,
    virtualBackground: currentVirtualBackground,
    afterJoinCallback: afterJoinCleanUp,
    autoSubscribe: true,
    ...joinOptions,
  }

  const mergedStyles = getMergedClassNames(zocksStyle, styles)

  const JoinPageLocalStreamsElement = components.JoinPageLocalStreams ?? JoinPageLocalStreams
  const JoinPageHeaderElement = components.JoinPageHeader ?? JoinPageHeader
  const JoinPageRoomInputElement = components.JoinPageRoomInput ?? JoinPageRoomInput
  const JoinPageRoomButtonsElement = components.JoinPageRoomButtons ?? JoinPageRoomButtons

  return (
    <div className={getClassName('join-page', mergedStyles)}>
      <JoinPageLocalStreamsElement styles={mergedStyles} localMedia={localMedia} baseJoinOptions={baseJoinOptions} />
      <div className={getClassName('join-page__controls', mergedStyles)}>
        <JoinPageHeaderElement styles={mergedStyles} />
        <JoinPageRoomInputElement
          styles={mergedStyles}
          initialRoomJoinInputValue={initialRoomJoinInputValue}
          initialRoomJoinSelectValue={initialRoomJoinSelectValue}
          joinAction={joinAction}
          baseJoinOptions={baseJoinOptions}
        />
        <JoinPageRoomButtonsElement
          styles={mergedStyles}
          joinAction={joinAction}
          createRoomAction={createRoomAction}
          baseJoinOptions={baseJoinOptions}
          onNewRoomCreated={onNewRoomCreated}
          disabled={newMeetingDisabled}
        />
      </div>
    </div>
  )
}
