import { useEffect, useRef } from 'react'

import Box from '../box'
import { omitThemingProps, useStyleConfig, vui, VuiComponent } from '../core'
import { Tag } from '../tag'
import { cs } from '../utils'
import { ChatInputStatus, ChatProps } from './chat.types'
import ChatInput from './chatInput'
import ChatMessage from './chatMessage'

/**
 * Displays a chat interface with messages and actions.
 */
export const Chat = vui<'div', ChatProps>((props, ref) => {
  const {
    className,
    children,
    inputStatus = ChatInputStatus.Default,
    messages,
    helpText,
    maxTextareaHeight = 120,
    processingMessage,
    suggestions,
    onNewTopicClick,
    onSuggestionClick,
    onSend,
    onStop,
    ...rest
  } = omitThemingProps(props)

  const styles = useStyleConfig('Chat', props)

  const messagesEndRef = useRef<HTMLDivElement>(null)

  const scrollDown = () => messagesEndRef.current?.scrollIntoView({ behavior: 'smooth' })

  useEffect(scrollDown, [messages, children])

  return (
    <Box
      className={cs('vui-chat', className)}
      ref={ref}
      {...styles.chat}
      h="100%"
      justifyContent="space-between"
      {...rest}
    >
      <Box className={cs('vui-chat-messages')} {...styles?.messages}>
        {messages?.length ? messages.map((message, key) => <ChatMessage key={key} {...message} />) : children}
        <div ref={messagesEndRef} />
      </Box>
      <Box column>
        {!!suggestions?.length && (
          <Box className={cs('vui-chat-suggestions')} {...styles?.suggestions} mb="24px" mt="8px">
            {suggestions?.map(suggestion => (
              <Tag
                cursor={inputStatus === ChatInputStatus.Default ? 'pointer' : undefined}
                disabled={inputStatus !== ChatInputStatus.Default}
                key={suggestion}
                mb="6px"
                ml="6px"
                onClick={() => onSuggestionClick?.(suggestion)}
              >
                {suggestion}
              </Tag>
            ))}
          </Box>
        )}
        <ChatInput
          helpText={helpText}
          maxTextareaHeight={maxTextareaHeight}
          onNewTopicClick={onNewTopicClick}
          onSend={onSend}
          onStop={onStop}
          processingMessage={processingMessage}
          status={inputStatus}
        />
      </Box>
    </Box>
  )
}) as VuiComponent<'div', ChatProps> & {
  Message: typeof ChatMessage
  Input: typeof ChatInput
}

Chat.Message = ChatMessage
Chat.Input = ChatInput
Chat.displayName = 'Chat'
export default Chat
