import React, { useCallback, useState } from 'react'
import ReactDOM from 'react-dom'
import { RoomInfo } from '@zocks-communications/client-sdk-js'
import { useLeaveOnUnload, useZocksActions, useZocksSession, ZocksChatActions } from '../../store'
import {
  CombinedChat,
  JoinPage,
  Participants,
  RoomControls,
  ViewSwitcher,
  OnlineParticipantsList,
  getMergedClassNames,
  StyledComponent,
  getClassName,
} from '../../components'
import zocksStyle from './Meeting.module.scss'

export const Meeting: React.FC<StyledComponent> = ({ styles }) => {
  const mergedStyles = getMergedClassNames(zocksStyle, styles)

  const { sessionActions, localMediaActions, chatActions, transcriptionActions } = useZocksActions({
    apiBaseUrl: 'https://api.zocks.io/v1',
    accountId: 'db8mt16gxt8ueddw',
  })
  const { roomId, roomName, localParticipantIsConnected } = useZocksSession()
  useLeaveOnUnload(sessionActions.leave)

  const [newRoom, setNewRoom] = useState<RoomInfo | null>(null)
  const ExtraButtonsElement: React.FC<StyledComponent> = useCallback(
    ({ styles }) => <ExtraButtons styles={styles} chatActions={chatActions} />,
    [chatActions]
  )

  return (
    <div className={getClassName('meeting', mergedStyles)}>
      <h1>Example</h1>
      <div>{'Room id: ' + roomId}</div>
      <div>{'Room name: ' + roomName}</div>
      <div>{'Connected: ' + localParticipantIsConnected}</div>
      {!localParticipantIsConnected ? (
        <>
          <JoinPage
            styles={mergedStyles}
            createRoomAction={sessionActions.createRoom}
            joinAction={sessionActions.join}
            onNewRoomCreated={(roomInfo) => setNewRoom(roomInfo)}
          />
          {newRoom && <div>{`New room created: ${JSON.stringify(newRoom)}`}</div>}
        </>
      ) : (
        <>
          <ViewSwitcher styles={mergedStyles} />
          <Participants styles={mergedStyles} speakerPageSize={4} />
          <RoomControls
            mediaActions={localMediaActions}
            leaveAction={sessionActions.leave}
            transcriptionActions={transcriptionActions}
            styles={mergedStyles}
            components={{ ExtraComponent: ExtraButtonsElement }}
          />
        </>
      )}
    </div>
  )
}

const ExtraButtons: React.FC<{ styles?: { [key: string]: string }; chatActions: ZocksChatActions }> = ({
  chatActions,
  styles,
}) => {
  const [showParticipantsList, setShowParticipantsList] = useState(false)
  const [showChat, setShowChat] = useState(false)

  return (
    <>
      <div className={getClassName('meeting__participants-list', styles)} id='participants-list-root' />
      <div className={getClassName('meeting__chat', styles)} id='chat-root' />
      {showParticipantsList &&
        ReactDOM.createPortal(
          <OnlineParticipantsList dismiss={() => setShowParticipantsList(false)} />,
          document.getElementById('participants-list-root')!
        )}
      {showChat &&
        ReactDOM.createPortal(
          <CombinedChat chatActions={chatActions} dismiss={() => setShowChat(false)} />,
          document.getElementById('chat-root')!
        )}
      <div className={getClassName('meeting__participants-list-button-container', styles)}>
        <button
          className={getClassName('meeting__participants-list-button', styles)}
          disabled={showParticipantsList}
          onClick={() => setShowParticipantsList(true)}
        >
          <label htmlFor='meeting__participants-list-button'>Show Participants</label>
        </button>
      </div>
      <div className={getClassName('meeting__other-control-buttons-container', styles)}>
        <div className={getClassName('meeting__chat-button-container', styles)}>
          <button
            className={getClassName('meeting__chat-button', styles)}
            disabled={showChat}
            onClick={() => setShowChat(true)}
          >
            <label htmlFor='meeting_chat-button'> Show Chat </label>
          </button>
        </div>
      </div>
    </>
  )
}
