import dayjs from 'dayjs';
import React, { useEffect, useRef, useState } from 'react';
import { ErrorBoundary } from 'react-error-boundary';
import { FaTimes } from 'react-icons/fa';
import styled from 'styled-components';
import { uiColors } from '../../constants/uiColors';
import { ChatMessage } from '../ChatRevamp/types';

export interface IStyles {
  textColor?: string;
  buttonColor?: string;
  buttonBackgroundColor?: string;
  width?: string;
  height?: string;
}

export interface IEmitter {
  _id: string;
  name: string;
}

export interface IChatProps {
  chatMessages: ChatMessage[];
  onSendChatMessage: (message: string) => void;
  onCloseButton: () => void;
  onFocus?: () => void;
  onBlur?: () => void;
  opacity?: number;
  sendMessage: boolean;
  styles?: IStyles;
  isExpanded: boolean;
}

export const Chat: React.FC<IChatProps> = ({
  chatMessages,
  onSendChatMessage,
  onCloseButton,
  onFocus,
  onBlur,
  styles = {
    textColor: '#ff6600',
    buttonColor: '#ff6600',
    buttonBackgroundColor: '#333',
    width: '100%',
    height: '100%',
  },
  isExpanded,
}) => {
  const [message, setMessage] = useState('');
  const inputRef = useRef<HTMLInputElement>(null);

  useEffect(() => {
    if (isExpanded) {
      scrollChatToBottom();
    }
    inputRef.current?.focus();
  }, [chatMessages, isExpanded]);

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

  const handleSubmit = (event: React.FormEvent<HTMLFormElement>) => {
    event.preventDefault();
    if (!message.trim()) return;
    onSendChatMessage(message);
    setMessage('');
  };

  const truncateName = (name: string, maxLength: number = 10) => {
    return name.length > maxLength ? name.slice(0, maxLength) + '...' : name;
  };

  const formatMessage = (chatMessage: ChatMessage) => {
    const timestamp = dayjs(chatMessage.createdAt).format('HH:mm');
    const truncatedName = truncateName(chatMessage.emitter.name);
    return `${timestamp} ${truncatedName}: ${chatMessage.message}`;
  };

  return (
    <ChatContainer
      width={styles.width || 'auto'}
      height={styles.height || 'auto'}
      isExpanded={isExpanded}
    >
      {isExpanded && (
        <ErrorBoundary fallback={<p>Oops! Your chat has crashed.</p>}>
          <CloseButton onClick={onCloseButton}>
            <FaTimes />
          </CloseButton>
          <MessagesContainer className="chat-body">
            {chatMessages.map((chatMessage, index) => (
              <Message
                color={styles.textColor || uiColors.yellow}
                key={`${chatMessage._id}_${index}`}
              >
                {formatMessage(chatMessage)}
              </Message>
            ))}
          </MessagesContainer>
        </ErrorBoundary>
      )}
      <Form onSubmit={handleSubmit} isExpanded={isExpanded}>
        <TextField
          ref={inputRef}
          value={message}
          onChange={e => setMessage(e.target.value)}
          type="text"
          autoComplete="off"
          onFocus={onFocus}
          onBlur={onBlur}
          onPointerDown={onFocus}
          placeholder="Type your message..."
        />
        <SendButton type="submit" disabled={!message.trim()}>
          ▶
        </SendButton>
      </Form>
    </ChatContainer>
  );
};

interface IContainerProps {
  width: string;
  height: string;
}

interface IMessageProps {
  color: string;
}

const ChatContainer = styled.div<IContainerProps & { isExpanded: boolean }>`
  width: ${props => props.width};
  height: ${props => (props.isExpanded ? props.height : 'auto')};
  background-color: rgba(30, 30, 30, 0.3);
  display: flex;
  flex-direction: column;
  position: relative;
  border-radius: 8px;
  border: 1px solid rgba(0, 0, 0, 0.1);
  overflow: hidden;
`;

const CloseButton = styled.button`
  position: absolute;
  top: 8px;
  right: 8px;
  background-color: transparent;
  border: none;
  color: white;
  font-size: 16px;
  cursor: pointer;
  z-index: 1;
`;

const MessagesContainer = styled.div`
  flex-grow: 1;
  overflow-y: auto;
  padding: 12px;
  margin-bottom: 8px;

  scrollbar-width: thin;
  scrollbar-color: rgba(51, 51, 51, 0.4) rgba(30, 30, 30, 0.4);

  &::-webkit-scrollbar {
    width: 6px;
  }

  &::-webkit-scrollbar-track {
    background: rgba(30, 30, 30, 0.4);
  }

  &::-webkit-scrollbar-thumb {
    background-color: rgba(51, 51, 51, 0.4);
    border-radius: 3px;
  }
`;

const Message = styled.div<IMessageProps>`
  margin-bottom: 6px;
  color: ${({ color }) => color};
  font-family: 'Press Start 2P', cursive;
  font-size: 0.7rem;
  line-height: 1.4;
  word-break: break-word;
`;

const Form = styled.form<{ isExpanded: boolean }>`
  display: flex;
  padding: 8px;
  background-color: rgba(42, 42, 42, 0.4);
  border-radius: ${props => (props.isExpanded ? '0' : '8px')};
`;

const TextField = styled.input`
  flex-grow: 1;
  background-color: rgba(26, 26, 26, 0.6);
  color: #ff6600;
  border: 1px solid rgba(51, 51, 51, 0.6);
  border-radius: 4px;
  padding: 8px;
  margin-right: 8px;
  font-family: 'Press Start 2P', cursive;
  font-size: 0.7rem;
  height: 32px;
  transition: border-color 0.3s, background-color 0.3s;

  &::placeholder {
    color: rgba(255, 255, 255, 0.5);
    font-size: 0.6rem;
  }

  &:focus {
    outline: none;
    border-color: #ff6600;
    background-color: rgba(42, 42, 42, 0.9);
  }
`;

const SendButton = styled.button`
  background-color: transparent;
  color: #ff6600;
  border: none;
  padding: 8px 12px;
  font-size: 14px;
  cursor: pointer;
  transition: opacity 0.3s ease;

  &:disabled {
    opacity: 0.5;
    cursor: not-allowed;
  }
`;
