import React from 'react';
import { observer } from 'mobx-react';
import { CSSProperties, css } from 'glamor';
import { useLocalStyles } from '../styles/defaults/useLocalStyles';
import { ApphouseComponent } from '../components/component.interfaces';
import { ChatMessage } from '../models/Chat';
import { ChatBubble, ChatBubbleStyles } from '../components/chat/ChatBubble';
import { getUniqueId } from '../utils/string/getUniqueId';
import { HiddenScrollbarStyle } from '../styles/defaults/scrollbars';

/**
 * Interface for styles to be applied to the ChatHistory component.
 */
export interface ChatHistoryStyles {
  container?: CSSProperties;
  chatBubble?: ChatBubbleStyles;
}
/**
 * Interface for the ChatHistory component.
 */
export interface ChatHistoryProps extends ApphouseComponent<ChatHistoryStyles> {
  /**
   * The chat history.
   */
  history?: ChatMessage[];
  /**
   * The id of the user that is using the chat.
   * It will be used to determine if the message goes to the left or right.
   * @example 'user' the message will be displayed on the right
   */
  selfUserId: string;
  /**
   * The background color of the surface where the input is.
   * this is used to make the bubble background of the chat, match the background of where it is placed.
   * @optional
   * @default 'surface'
   */
  surfaceBackground?: string;
  /**
   * The id of the component. If provided, 'chat-history-${id}' will be id of the container.
   * This is important for scroll to view. If clashing ids, scroll might be triggered on the wrong component.
   * @optional if not provided, a random id will be generated.
   */
  id?: string;
}
/**
 * It displays a chat history decorated with message bubbles.
 */
export const ChatHistory: React.FC<ChatHistoryProps> = observer((props) => {
  const { styleOverwrites, gutters, history, surfaceBackground, id } = props;
  const componentStyles: ChatHistoryStyles = {
    container: {
      width: '100%',
      display: 'flex',
      flexDirection: 'column',
      ...HiddenScrollbarStyle
    }
  };
  const localStyles = useLocalStyles<ChatHistoryStyles>(
    componentStyles,
    styleOverwrites,
    gutters
  );

  const ref = React.useRef<HTMLDivElement>(null);
  React.useEffect(() => {
    if (ref.current) {
      ref.current.scrollIntoView({
        behavior: 'smooth',
        block: 'end',
        inline: 'end'
      });
    }
  }, [history]);
  return (
    <div
      id={`chat-history-${id || getUniqueId()}`}
      ref={ref}
      data-xray="ChatHistory"
      {...css(localStyles.container)}
    >
      {history?.map((message) => {
        const isSelf = message.userId === props.selfUserId;
        return (
          <ChatBubble
            key={message.id}
            direction={isSelf ? 'right' : 'left'}
            surfaceBackground={surfaceBackground}
            styleOverwrites={localStyles.chatBubble}
          >
            {message.content}
          </ChatBubble>
        );
      })}
    </div>
  );
});
