import classNames from 'classnames'
import React from 'react'
import { getClassName, getMergedClassNames } from '../../components'
import { useZocksStore } from '../../app'
import { selectIsConnecting, useLeaveOnUnload, useZocksSession } from '../../store'
import { useFullScreen } from './hooks'
import { Loader } from './OneOnOneParticipantView/Loader/Loader'
import { OneOnOneJoinPage } from './OneOnOneJoinPage'
import { OneOnOneParticipantView } from './OneOnOneParticipantView'
import { OneOnOneRoomControls } from './OneOnOneRoomControls'
import { OneOnOneMeetingProps } from './models'
import zocksStyle from './OneOnOneMeeting.module.scss'

export const OneOnOneMeeting: React.FC<OneOnOneMeetingProps> = ({ styles, zocksActions, joinOptions, components }) => {
  const mergedStyles = getMergedClassNames(zocksStyle, styles)
  const isConnecting = useZocksStore(selectIsConnecting)
  const { isInFullscreen, toggleFullScreen } = useFullScreen()
  const { localParticipantIsConnected } = useZocksSession()
  useLeaveOnUnload(zocksActions.sessionActions.leave)

  const JoinLoaderElement = components?.Loader ?? Loader

  return (
    <div
      className={classNames(getClassName('oneonone-meeting__container', mergedStyles), {
        [getClassName('oneonone-meeting--full-screen', mergedStyles)]: isInFullscreen,
      })}
    >
      {!localParticipantIsConnected ? (
        isConnecting ? (
          <JoinLoaderElement styles={mergedStyles} />
        ) : (
          <OneOnOneJoinPage
            styles={mergedStyles}
            joinOptions={joinOptions}
            joinAction={zocksActions.sessionActions.join}
            components={components?.joinPage}
          />
        )
      ) : (
        <>
          <OneOnOneParticipantView components={components?.participant} styles={mergedStyles} />
          <OneOnOneRoomControls
            styles={mergedStyles}
            zocksActions={zocksActions}
            isInFullscreen={isInFullscreen}
            toggleFullscreen={toggleFullScreen}
            components={components?.roomControls}
          />
        </>
      )}
    </div>
  )
}
