Untitled

mail@pastecode.io avatar
unknown
plain_text
a year ago
2.4 kB
2
Indexable
import React, {useEffect, useState} from 'react'

import {useRouter} from 'next/router'
import {useTranslation} from 'react-i18next'

import useUserContext from 'common/hooks/useUserContext'
import {postAsync} from 'services/cpBackendApi'

import ChatbotActivator from './components/ActivatorButton'
import ChatWindow from './components/ChatWindow'

const STATUS_CODE_OK = 200
const NO_SHOW_PAGES = {
  TOURPAGE: 'tourpage',
  CREATEPAGE: 'create'
}

const Chatbot = () => {
  const {t} = useTranslation()
  const {user} = useUserContext()
  const router = useRouter()

  const userGreeting = user.firstName ? user.firstName + '!' : ''
  const [isChatVisible, setIsChatVisible] = useState(false)
  const [isWaitingForResponse, setIsWaitingForResponse] = useState(false)
  const [messages, setMessages] = useState([
    {
      type: 'chatbot',
      text: t('CHATBOT_GREETING', {USER_NAME: userGreeting})
    }
  ])

  const openChat = isOpen => {
    setIsChatVisible(isOpen)
  }

  const toggleChat = () => {
    setIsChatVisible(!isChatVisible)
  }

  const askQuestion = async question => {
    setMessages(oldMessages => [
      ...oldMessages,
      {
        type: 'user',
        text: question
      }
    ])

    setIsWaitingForResponse(true)
    const response = await postAsync('chatbot/chatbot-ask', {question})
    setIsWaitingForResponse(false)

    if (response.status === STATUS_CODE_OK) {
      setMessages(oldMessages => [
        ...oldMessages,
        {
          type: 'chatbot',
          text: response.data.message
        }
      ])
    }
  }

  useEffect(() => {
    if (messages.length === 1) {
      setMessages([
        {
          type: 'chatbot',
          text: t('CHATBOT_GREETING', {USER_NAME: userGreeting})
        }
      ])
    }
  }, [user.firstName])

  return (
    <>
      {!router.route.includes(NO_SHOW_PAGES.TOURPAGE) &&
        !router.route.includes(NO_SHOW_PAGES.CREATEPAGE) && (
          <>
            <ChatWindow
              messages={messages}
              askQuestion={askQuestion}
              isVisible={isChatVisible}
              closeChat={() => openChat(false)}
              shouldShowLoadingDots={isWaitingForResponse}
            />
            <ChatbotActivator shouldShowOnMobile={!isChatVisible} toggleChat={toggleChat} />
          </>
        )}
    </>
  )
}

export default Chatbot