import React, { useCallback } from 'react';
import styled from '@emotion/styled';
import { color, fontWeight } from 'styled-system';
import { useTheme } from 'hooks';
import { COLOR_DARK, COLOR_LIGHT } from 'theme';
import {
  Maybe,
  RichTextContentSegment,
  RichTextContentStringColorEnum,
  RichTextContentStringStyle,
} from 'expo-schema';

const RichText = styled('span')(color, fontWeight, {
  fontFamily: 'CircularStd-Book',
});
const ContentWrapper = styled.div``;

export const MessageContent: React.FC<RichTextContentProps> = ({ richTextContent }) => {
  const { activeThemeMode } = useTheme();

  const textColor = activeThemeMode === 'dark' ? COLOR_DARK.title : COLOR_LIGHT.title;
  const { id: segmentId, strings } = richTextContent;

  const getTextDecoration = useCallback((style: Maybe<RichTextContentStringStyle> | undefined) => {
    const underLine = style?.underline ? 'underline' : 'none';
    return style?.strikethrough ? 'line-through' : underLine;
  }, []);

  const getFontStyle = (style: RichTextContentStringStyle) =>
    style?.italics ? 'italic' : 'normal';

  return (
    <ContentWrapper
      style={{
        fontSize: 14,
        color: textColor,
        fontFamily: 'CircularStd-Book',
        flexWrap: 'wrap',
        outline: 'none',
      }}
      key={segmentId}
    >
      {strings.map(({ id, style, value }) => {
        return (
          <RichText
            key={id}
            id={id}
            data-is-code={style?.codeStyle}
            style={{
              fontStyle: getFontStyle(style as RichTextContentStringStyle),
              fontWeight: style?.bold ? 'bold' : 'normal',
              textDecorationLine: getTextDecoration(style),
              color:
                style?.textColor === RichTextContentStringColorEnum.Default.toLowerCase()
                  ? textColor
                  : style?.textColor,
            }}
            backgroundColor={style?.codeStyle ? 'primary' : 'transparent'} // TODO:sarmad need to change background color
          >
            {value}
          </RichText>
        );
      })}
    </ContentWrapper>
  );
};

export type RichTextContentProps = {
  richTextContent: RichTextContentSegment;
};
