import { ILocalChatMessage } from '@rpg-engine/shared';
import dayjs from 'dayjs';
import React, { useEffect, useState } from 'react';
import { ErrorBoundary } from 'react-error-boundary';
import styled from 'styled-components';
import { uiColors } from '../../constants/uiColors';
import { uiFonts } from '../../constants/uiFonts';
import { Button, ButtonTypes } from '../Button';
import { Input } from '../Input';
import { RPGUIContainer, RPGUIContainerTypes } from '../RPGUI/RPGUIContainer';
import { Column } from '../shared/Column';

interface IEmitter {
  _id: string;
  name: string;
}
export interface IChatDeprecatedProps {
  chatMessages: ILocalChatMessage[];
  onSendChatMessage: (message: string) => void;
  onCloseButton: () => void;
  onFocus?: () => void;
  onBlur?: () => void;
  opacity?: number;
  width?: string;
  height?: string;
}

export const ChatDeprecated: React.FC<IChatDeprecatedProps> = ({
  chatMessages,
  onSendChatMessage,
  opacity = 1,
  width = '100%',
  height = '250px',
  onCloseButton,
  onFocus,
  onBlur,
}) => {
  const [message, setMessage] = useState('');

  useEffect(() => {
    scrollChatToBottom();
  }, []);

  useEffect(() => {
    scrollChatToBottom();
  }, [chatMessages]);

  const scrollChatToBottom = () => {
    const scrollingElement = document.querySelector('.chat-body');
    if (scrollingElement) {
      scrollingElement.scrollTop = scrollingElement.scrollHeight;
    }
  };

  const handleSubmit = (event: React.SyntheticEvent<HTMLFormElement>) => {
    event.preventDefault();
    onSendChatMessage(message);
    setMessage('');
  };
  const getInputValue = (value: string) => {
    setMessage(value);
  };

  const onRenderMessageLines = (
    emitter: IEmitter,
    createdAt: string | undefined,
    message: string
  ) => {
    return `${dayjs(createdAt || new Date()).format('HH:mm')} ${
      emitter?.name ? `${emitter.name}: ` : 'Unknown: '
    } ${message}`;
  };

  const onRenderChatMessages = (chatMessages: ILocalChatMessage[]) => {
    return chatMessages?.length ? (
      chatMessages?.map(({ _id, createdAt, emitter, message }, index) => (
        <MessageText key={`${_id}_${index}`}>
          {onRenderMessageLines(emitter, createdAt as string, message)}
        </MessageText>
      ))
    ) : (
      <MessageText>No messages available.</MessageText>
    );
  };

  return (
    <Container>
      <CustomContainer
        type={RPGUIContainerTypes.FramedGrey}
        width={width}
        height={height}
        className="chat-container"
        opacity={opacity}
      >
        <ErrorBoundary fallback={<p>Oops! Your chat has crashed.</p>}>
          {onCloseButton && (
            <CloseButton onPointerDown={onCloseButton}>X</CloseButton>
          )}
          <RPGUIContainer
            type={RPGUIContainerTypes.FramedGrey}
            width={'100%'}
            height={'80%'}
            className="chat-body dark-background"
          >
            {onRenderChatMessages(chatMessages)}
          </RPGUIContainer>

          <Form onSubmit={handleSubmit}>
            <Column flex={70}>
              <CustomInput
                value={message}
                id="inputMessage"
                onChange={e => getInputValue(e.target.value)}
                height={20}
                className="chat-input dark-background"
                type="text"
                autoComplete="off"
                onFocus={onFocus}
                onBlur={onBlur}
              />
            </Column>
            <Column justifyContent="flex-end">
              <Button
                buttonType={ButtonTypes.RPGUIButton}
                id="chat-send-button"
              >
                Send
              </Button>
            </Column>
          </Form>
        </ErrorBoundary>
      </CustomContainer>
    </Container>
  );
};

const Container = styled.div`
  position: relative;
`;

const CloseButton = styled.div`
  position: absolute;
  top: 2px;
  right: 0px;
  color: white;
  z-index: 22;
  font-size: 0.7rem;
`;

const CustomInput = styled(Input)`
  height: 30px;
  width: 100%;

  .rpgui-content .input {
    min-height: 39px;
  }
`;

interface ICustomContainerProps {
  opacity: number;
}

const CustomContainer = styled(RPGUIContainer)`
  display: block;

  opacity: ${(props: ICustomContainerProps) => props.opacity};

  &:hover {
    opacity: 1;
  }

  .dark-background {
    background-color: ${uiColors.darkGray} !important;
  }

  .chat-body {
    &.rpgui-container.framed-grey {
      background: unset;
    }
    max-height: 170px;
    overflow-y: auto;
  }
`;

const Form = styled.form`
  display: flex;
  width: 100%;
  justify-content: center;
  align-items: center;
`;

const MessageText = styled.p`
  display: block !important;
  width: 100%;
  font-size: ${uiFonts.size.xsmall} !important;
  overflow-y: auto;
  margin: 0;
`;
