import { useI18n } from 'domains/i18n/hooks'
import { MessageInfo, MessageMessage } from 'domains/store/store.types'
import { useVisibility } from 'domains/visibility/hooks'
import { className } from 'lib/css'
import PrivacyDisclaimer from 'ui/components/layout/privacy-disclaimer'
import {
  useSeamlyIsLoading,
  useSkiplinkElement,
  useSkiplinkTarget,
  useSkiplinkTargetFocusing,
} from 'ui/hooks/seamly-hooks'
import { useEvents } from 'ui/hooks/seamly-state-hooks'
import useDebounce from 'ui/hooks/use-debounce'
import AbortTransactionButton from '../entry/abort-transaction-button/abort-transaction-button'
import ComponentFilter from './component-filter'
import Event from './event/event'
import Loader from './loader'

const Events = () => {
  const events = useEvents()
  let prevParticipant:
    | MessageInfo['participant']
    | MessageMessage['participant']
  return (
    <>
      {events.map((event) => {
        const { type, payload } = event

        let participantChanged = false
        if (type === 'info' || type === 'message') {
          const { participant, fromClient } = payload
          const currentParticipant = fromClient
            ? 'seamly-client-participant'
            : participant

          if (event.type !== 'info' && prevParticipant !== currentParticipant) {
            participantChanged = true
          }

          prevParticipant = currentParticipant
        }

        return (
          <Event
            key={event.payload.key || event.payload.id}
            event={event}
            newParticipant={participantChanged}
          />
        )
      })}
    </>
  )
}

const Conversation = () => {
  const { t } = useI18n()
  const isLoading = useSeamlyIsLoading()
  const debouncedIsLoading = useDebounce(isLoading, isLoading ? 0 : 20)
  const { isOpen } = useVisibility()
  const skiplinkElementId = useSkiplinkElement()
  const skiplinkTargetId = useSkiplinkTarget()
  const focusSkiplinkTarget = useSkiplinkTargetFocusing()

  const onClickHandler = (e) => {
    e.preventDefault()
    focusSkiplinkTarget()
  }

  return (
    <>
      {isOpen && (
        <a
          id={skiplinkElementId}
          className={className('skip-link')}
          href={`#${skiplinkTargetId}`}
          onClick={onClickHandler}
        >
          {t('skiplinkText')}
        </a>
      )}

      <div className={className('chat__body')}>
        <div className={className('conversation__container')}>
          <PrivacyDisclaimer />
          <div role="log" aria-label={t('chat.srLabel')}>
            <ol className={className('conversation')}>
              <ComponentFilter>
                <Events />
              </ComponentFilter>
              {debouncedIsLoading ? <Loader /> : null}
              <AbortTransactionButton />
            </ol>
          </div>
        </div>
      </div>
    </>
  )
}

export default Conversation
