import { useUserHasResponded } from 'domains/app/hooks'
import { setHasResponded } from 'domains/app/slice'
import { useConfig } from 'domains/config/hooks'
import { useI18n } from 'domains/i18n/hooks'
import { useAppDispatch } from 'domains/store'
import { useTranslatedEventData } from 'domains/translations/hooks'
import { className } from 'lib/css'
import { randomId } from 'lib/id'
import { useCallback, useMemo, useState } from 'preact/hooks'
import MessageContainer from 'ui/components/conversation/message-container'
import SuggestionsList from 'ui/components/suggestions/suggestions-list'
import { useSeamlyHasConversation } from 'ui/hooks/seamly-api-hooks'
import { useEvents, useSeamlyCommands } from 'ui/hooks/seamly-hooks'
import { actionTypes } from 'ui/utils/seamly-utils'

export const useSuggestions = (event) => {
  const { payload } = event
  const { body: suggestions } = useTranslatedEventData(event)

  return {
    suggestions,
    payload,
  }
}

const ConversationSuggestions = ({ event, ...props }) => {
  const [isExpanded, setIsExpanded] = useState(true)
  const dispatch = useAppDispatch()
  const userHasResponded = useUserHasResponded()
  const { addMessageBubble, emitEvent, sendAction } = useSeamlyCommands()
  const hasConversation = useSeamlyHasConversation()
  const { suggestions, payload } = useSuggestions(event)
  const { showSuggestions } = useConfig()
  const events = useEvents()

  const { t } = useI18n()
  const headingText = t('suggestions.headingText')
  const footerText = t('suggestions.footerText')

  // We check if there is at least one last transaction
  // to avoid rendering the suggestions before prior events are rendered.
  const hasLastTransactionEvent = useMemo(
    () =>
      events.some(
        ({ payload: eventPayload, type }) =>
          type === 'message' && eventPayload?.transactionLast,
      ),
    [events],
  )

  const handleClick = useCallback(
    ({
      id,
      question,
    }: {
      id: string | number | undefined
      question?: string | undefined
    }) => {
      // Do not allow interaction without a conversation
      if (!hasConversation()) {
        return
      }

      setIsExpanded(false)
      dispatch(setHasResponded(true))

      const transactionId = randomId()
      const action = {
        type: actionTypes.custom,
        originMessage: payload.id,
        body: {
          type: 'faqclick',
          body: {
            faqId: id,
            faqQuestion: question,
          },
        },
        transactionId,
      }

      // @todo Refactor to 'suggestionclick'
      sendAction(action)
      addMessageBubble(question, transactionId)
      emitEvent(`action.${action.type}`, action)
    },
    [
      addMessageBubble,
      dispatch,
      emitEvent,
      hasConversation,
      payload.id,
      sendAction,
    ],
  )

  if (
    !isExpanded ||
    userHasResponded ||
    !hasLastTransactionEvent ||
    !showSuggestions
  ) {
    return null
  }

  return (
    <div className={className('suggestions', 'suggestions--conversation')}>
      {headingText && (
        <p className={className('suggestions__heading')}>{headingText}</p>
      )}
      <MessageContainer
        type="suggestions"
        showParticipant={false}
        event={event}
        {...props}
      >
        <SuggestionsList
          className="suggestions__list--conversation"
          onClickSuggestion={handleClick}
          suggestions={suggestions}
        />
        {footerText && (
          <p className={className('suggestions__footer')}>{footerText}</p>
        )}
      </MessageContainer>
    </div>
  )
}

export default ConversationSuggestions
