import { useStartChatIcon } from 'domains/config/hooks'
import { useI18n } from 'domains/i18n/hooks'
import { selectHasError } from 'domains/interrupt/selectors'
import { useVisibility } from 'domains/visibility/hooks'
import { className } from 'lib/css'
import { useSelector } from 'react-redux'
import {
  useSeamlyCurrentAgent,
  useSeamlyHeaderData,
  useSeamlyUnreadCount,
} from 'ui/hooks/seamly-hooks'
import Icon from './icon'

const AgentInfo = () => {
  const { t } = useI18n()
  const { title, subTitle } = useSeamlyHeaderData()
  const unreadMessageCount = useSeamlyUnreadCount()
  const { isOpen } = useVisibility()
  const currentAgent = useSeamlyCurrentAgent()
  const hasError = useSelector(selectHasError)
  const startChatIcon = useStartChatIcon()
  const src = currentAgent?.avatar ?? startChatIcon
  const displaySubtitle = hasError ? '' : subTitle

  const classNames = ['message-count']

  if (isOpen) {
    classNames.push('message-count__hide')
  }

  if (unreadMessageCount === 0) {
    classNames.push('message-count__empty')
  }

  return displaySubtitle || !isOpen ? (
    <div className={className('agent-info')}>
      <div className={className('agent-info__graphic')}>
        {src ? (
          <img
            className={className(currentAgent?.avatar ? 'avatar' : 'icon')}
            src={src}
            alt=""
          />
        ) : (
          <Icon name="avatar" size="32" alt="" />
        )}
        <span className={className(classNames)} aria-hidden="true">
          {unreadMessageCount}
        </span>
      </div>

      <div className={className('agent-info__body')}>
        <p className={className('agent-info__heading')}>
          {title ?? t('header.title')}
        </p>
        <p className={className('agent-info__text')}>{displaySubtitle}</p>
      </div>
    </div>
  ) : null
}

export default AgentInfo
