import { FC, useCallback } from 'react';
import { Col, Row } from 'components/layout';
import { Text } from 'components/text';
import { CloseThick, Pencil, QuoteReply, ReplyThread } from 'icons';
import { Divider } from 'components/divider';
import { Fab } from 'components/fab';
import { useTheme } from 'hooks';
import { editingMessageIdVar, isEditingMessageVar } from 'state-management/chat';
import { MessageFragment, RichTextContentSegment } from 'expo-schema';
import { Visible } from 'components/visible';
import { Content } from '../content';

const referenceIcons: Record<ReferenceMessageVariant, JSX.Element> = {
  reply: <ReplyThread />,
  quote: <QuoteReply />,
  edit: <Pencil />,
};

export const ReferenceMessage: FC<ReferenceMessageType> = ({ variant, message }) => {
  const { activeThemeMode } = useTheme();
  const lineBackgroundColor = activeThemeMode === 'dark' ? 'white' : 'primary';

  const closeEditingMessage = useCallback(() => {
    isEditingMessageVar(false);
    editingMessageIdVar('');
  }, []);

  const isMessage = message?.richTextContent && message?.richTextContent?.length > 0;

  return (
    <Col>
      <Row
        p="xs"
        backgroundColor="base-02-hover"
        alignItems="center"
        justifyContent="space-between"
      >
        <Row alignItems="center">
          {referenceIcons[variant]}
          <Divider
            mx="s"
            colorVariant="divider"
            size={3}
            backgroundColor={lineBackgroundColor}
            directionVariant="vertical"
            borderRadius={2}
          />
          <Col flexShrink={1}>
            <Row alignItems="center">
              <Text variant="body" color="title">
                {message?.userName?.first} {message?.userName?.last}
              </Text>
            </Row>
            <Visible if={isMessage as boolean}>
              <>
                {message?.richTextContent?.map((richTextContent) => {
                  return (
                    <Content
                      setRichTextContent={() => {}}
                      key={richTextContent.id}
                      placeholder=""
                      richTextContent={richTextContent as RichTextContentSegment}
                    />
                  );
                })}
              </>
            </Visible>
          </Col>
        </Row>
        <Fab
          onPress={closeEditingMessage}
          sizeVariant="medium"
          colorVariant="transparent"
          variant="plain"
          hoverColorVariant="base-02"
          centerElement={<CloseThick colorVariant="body" />}
        />
      </Row>
      <Divider directionVariant="horizontal" colorVariant="divider-02" />
    </Col>
  );
};

type ReferenceMessageType = ReferenceMessageProps;
type ReferenceMessageVariant = 'reply' | 'quote' | 'edit';

export interface ReferenceMessageProps {
  variant: ReferenceMessageVariant;
  message: MessageFragment;
}
