import { FC, useEffect, useRef, useState } from 'react';
import { GestureResponderEvent } from 'react-native';
import { useReactiveVar } from '@apollo/client';
import { useHover } from 'react-native-web-hooks';

import { useResponsiveLayout } from 'hooks';
import { CheckGroup, Eye, SyncBack } from 'icons';
import { Avatar, Text, Visible } from 'components';
import { MessageAction } from 'components/sheets';

import { Col, Container, Row, TouchableHighlight } from 'components/layout';
import { getMessageDateTime } from 'utils/dateTime';
import { MessageFragment, RichTextContentSegment } from 'expo-schema';
import { isMessageMoreActionOpenVar } from 'state-management/dialogs';
import { selectedMessageIdVar } from 'state-management/chat';
import { MessageContent } from 'components/rich-text';
import { MessageReactions } from '../message-reactions';
import { RoomCreated } from './room-created/RoomCreated';
import { File } from './file';
import { Replies } from './replies';

export const Message: FC<MessageProps> = ({ isThread, message, onLongPress, onHovered }) => {
  const { isMobile, isHandHeld } = useResponsiveLayout();
  const isMessageMoreActionOpen = useReactiveVar(isMessageMoreActionOpenVar);
  const selectedMessageId = useReactiveVar(selectedMessageIdVar);
  const [isMessageHovered, setIsMessageHovered] = useState(false);

  const keepHovered = selectedMessageId === message.id && isMessageMoreActionOpen;
  const messageRef = useRef(null);
  const isHovered = useHover(messageRef);

  const { id, richTextContent, replyCount, userName, userProfilePhotoUrl, createdAt } = message;

  const position = !isHandHeld
    ? messageRef.current &&
      (messageRef.current as unknown as HTMLDivElement).getBoundingClientRect()
    : null;

  useEffect(() => {
    if (isHovered) {
      if (onHovered) {
        onHovered(true);
        setIsMessageHovered(true);
      }
    } else {
      if (onHovered) {
        onHovered(false);
        setIsMessageHovered(false);
      }
    }
    if (keepHovered) {
      if (onHovered) {
        onHovered(true);
        setIsMessageHovered(true);
      }
    }
  }, [isHovered, onHovered, keepHovered]);

  const size = isMobile ? 30 : 38;
  const titleVariant = isThread ? 'caption' : 'body';
  const backgroundColor = isMessageHovered ? 'base-02-hover' : 'transparent';

  return (
    <Container ref={messageRef} py="2xs" px="m" backgroundColor={backgroundColor}>
      <Visible if={false}>
        <RoomCreated message={message} />
      </Visible>
      <Visible if={isMessageHovered}>
        <MessageAction position={position} messageId={id} isHovered={isMessageHovered} />
      </Visible>
      <Visible if={true}>
        <TouchableHighlight underlayColor={'transparent'} onLongPress={onLongPress}>
          <Row>
            <Avatar
              size={size}
              shapeVariant="square"
              colorVariant="base-02"
              title={userName?.first}
              uri={userProfilePhotoUrl}
            />
            <Col ml="xs" flexShrink={1}>
              <Row alignItems="center">
                <Text variant={titleVariant} color="title">
                  {userName?.first}
                  {''} {userName?.last}
                </Text>
                <Text mx="xs" variant="caption">
                  {getMessageDateTime(createdAt)}
                </Text>

                <Visible if={false}>
                  <Row alignItems="center">
                    <Eye />
                    <Text marginLeft="3xs" variant="caption">
                      {replyCount}
                    </Text>
                  </Row>
                </Visible>
                <Visible if={false}>
                  <Container mx="xs">
                    <CheckGroup colorVariant="body" />
                  </Container>
                </Visible>
                <Visible if={false}>
                  <Container ml="2xs">
                    <SyncBack />
                  </Container>
                </Visible>
              </Row>
              <Visible if={false}>
                <File status="downloading" message={message} />
              </Visible>
              {richTextContent?.map((richContent) => (
                <MessageContent
                  key={richContent.id}
                  richTextContent={richContent as RichTextContentSegment}
                />
              ))}
              <Visible if={false}>
                <MessageReactions reactions={[]} />
              </Visible>
              <Replies repliesCount={0} users={[]} />
            </Col>
          </Row>
        </TouchableHighlight>
      </Visible>
    </Container>
  );
};

export interface MessageProps {
  onHovered?: (value: boolean) => void;
  onLongPress?: ((event: GestureResponderEvent) => void) | undefined;
  isThread?: boolean;
  message: MessageFragment;
}
