import React from 'react'
import classNames from 'classnames'
import { DeviceSelectButton } from '../../DeviceSelectButton'
import { getClassName, getMergedClassNames, StyledComponent } from '../../common'
import { VideoControlButtonProps } from './models'
import zocksStyle from './VideoControlButton.module.scss'
import { DefaultVideoControlMenu } from './VideoControlMenu'
import { useZocksStore } from '../../../app'
import { selectVideoIsLoading } from '../../../store'

export const VideoControlButton: React.FC<VideoControlButtonProps> = ({
  videoIsOn,
  toggleVideo,
  onVideoDeviceSelected,
  components,
  styles,
}) => {
  const videoIsLoading = useZocksStore(selectVideoIsLoading)
  const mergedStyles = getMergedClassNames(zocksStyle, styles)

  const VideoControlMenuElement = components?.VideoControlMenu || DefaultVideoControlMenu
  const VideoLoadingIndicatorElement = components?.VideoLoadingIndicator || RingSpinner

  return (
    <div className={getClassName('video-button-container', mergedStyles)}>
      {videoIsLoading ? (
        <VideoLoadingIndicatorElement styles={mergedStyles} />
      ) : (
        <button id='zocks__video-button' className={getClassName('control-button', mergedStyles)} onClick={toggleVideo}>
          <div
            className={classNames({
              [getClassName('video-button--unmuted', mergedStyles)]: videoIsOn,
              [getClassName('video-button--muted', mergedStyles)]: !videoIsOn,
            })}
          />
          <label htmlFor='zocks__video-button'>{videoIsOn ? 'Disable Video' : 'Enable Video'}</label>
        </button>
      )}

      {onVideoDeviceSelected && (
        <DeviceSelectButton
          disabled={!videoIsOn || videoIsLoading}
          deviceKind={'videoinput'}
          styles={mergedStyles}
          onDeviceSelected={onVideoDeviceSelected}
          label={'Video devices'}
          components={{ SelectMenu: VideoControlMenuElement }}
        />
      )}
    </div>
  )
}

const RingSpinner: React.FC<StyledComponent> = ({ styles }) => {
  return (
    <div className={getClassName('ring-spinner', styles)} aria-busy={true} role='status'>
      <div></div>
      <div></div>
    </div>
  )
}
