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'
import { MissingScopeAction } from '../ScopedBlock'

export const JoinPage: React.FC<JoinPageProps> = ({
  joinAction,
  authActions,
  createRoomAction,
  initialRoomJoinInputValue = '',
  initialRoomJoinSelectValue = 'id',
  newMeetingDisabled = false,
  videoEnabledByDefault = false,
  audioEnabledByDefault = false,
  defaultVirtualBackground,
  onNewRoomCreated,
  joinOptions = {},
  components = {},
  styles,
  missingScopeAction = MissingScopeAction.DISABLE,
}) => {
  const { localMedia, afterJoinCleanUp } = useJoinPage(
    videoEnabledByDefault,
    audioEnabledByDefault,
    defaultVirtualBackground
  )
  const { localMediaJoinOptions } = localMedia

  const baseJoinOptions: Partial<JoinOptions> = {
    ...localMediaJoinOptions,
    autoCreate: false,
    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
          authActions={authActions}
          styles={mergedStyles}
          joinAction={joinAction}
          createRoomAction={createRoomAction}
          baseJoinOptions={baseJoinOptions}
          onNewRoomCreated={onNewRoomCreated}
          disabled={newMeetingDisabled}
          missingScopeAction={missingScopeAction}
        />
      </div>
    </div>
  )
}
