import React, { useState } from 'react'
import { useZocksStore } from '../../../app'
import { selectIsConnecting } from '../../../store'
import { ErrorResponse, getClassName, getMergedClassNames } from '../../common'
import { JoinPageRoomButtonsProps } from './models'
import zocksStyle from './JoinPageRoomButtons.module.scss'

export const JoinPageRoomButtons: React.FC<JoinPageRoomButtonsProps> = ({
  joinAction,
  createRoomAction,
  onNewRoomCreated,
  baseJoinOptions,
  disabled,
  styles,
  joinNewRoomButtonLabel = 'Start New Meeting',
  createNewRoomForLaterButtonLabel = 'Create New Meeting for Later',
}) => {
  const isConnecting = useZocksStore(selectIsConnecting)
  const [hasError, setHasError] = useState<boolean>(false)
  const [error, setError] = useState<string>('')

  const createNewRoom = async () => {
    if (createRoomAction) {
      const roomInfo = await createRoomAction()
      onNewRoomCreated && onNewRoomCreated(roomInfo)
    }
  }

  const joinErrorCallback = (e: ErrorResponse | string) => {
    setError(typeof e === 'string' ? e : e.errors.map((v) => v.message).join(', '))
    setHasError(true)
  }

  const joinOptions = {
    joinErrorCallback,
    ...baseJoinOptions,
  }

  const mergedStyles = getMergedClassNames(zocksStyle, styles)

  return (
    <>
      <div className={getClassName('join-page__controls-divider', mergedStyles)}>
        <span>OR</span>
      </div>
      <div className={getClassName('join-page__new-meeting-container', mergedStyles)}>
        <button
          className={`${getClassName('join-page__room-button', mergedStyles)} ${getClassName(
            'join-page__new-meeting-button',
            mergedStyles
          )}`}
          onClick={() => joinAction({ ...joinOptions, roomId: '', roomName: '', autoCreate: true })}
          disabled={isConnecting || disabled}
        >
          {joinNewRoomButtonLabel}
        </button>
        <button
          className={`${getClassName('join-page__room-button', mergedStyles)} ${getClassName(
            'join-page__create-new-meeting-button',
            mergedStyles
          )}`}
          onClick={createNewRoom}
          disabled={isConnecting || disabled}
        >
          {createNewRoomForLaterButtonLabel}
        </button>
        {hasError && <span className={getClassName('join-page__room-buttons-error', mergedStyles)}>{error}</span>}
      </div>
    </>
  )
}
