import React, { MutableRefObject, useCallback, useEffect, useRef, useState } from 'react';
import { TextInput as TextInputType } from 'react-native';
import { TextInput } from 'components/layout';
import { Text } from 'components/text';
import {
  Maybe,
  RichTextContentSegmentString,
  RichTextContentSegmentTypeEnum,
  RichTextContentStringStyle,
} from 'expo-schema';
import { localStyle } from 'utils/richText';
import { debounce, uniqueId } from 'lodash';
import { metrics } from 'config';
import { useTheme } from 'hooks';
import { COLOR_VALUES } from 'theme/color';
import { RichTextContentProps } from './Content.web';

const { INPUT_DEBOUNCE } = metrics.RICH_TEXT_EDITOR;

export const Content: React.FC<RichTextContentProps> = ({
  placeholder,
  richTextContent,
  setRichTextContent,
}) => {
  const { activeThemeMode } = useTheme();
  const [localStrings, setLocalStrings] = useState<RichTextContentSegmentString[]>([]);
  const richRef = useRef() as MutableRefObject<TextInputType>;
  const { id: segmentId, strings } = richTextContent;

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

  useEffect(() => {
    if (setRichTextContent) {
      if (localStrings.length > 0) {
        setRichTextContent({
          order: 1,
          id: uniqueId(),
          type: RichTextContentSegmentTypeEnum.Paragraph,
          strings: localStrings,
          variant: 'input',
        });
      }
    }
  }, [localStrings, setRichTextContent]);

  const handleChange = useCallback((value) => {
    const segments: string[] = value.trim().split(' ');
    const parsedSegments: RichTextContentSegmentString[] = segments.map((segment, index) => {
      return {
        order: index,
        value: ' ' + segment,
        style: localStyle,
      };
    }) as RichTextContentSegmentString[];
    setLocalStrings(parsedSegments);
  }, []);

  // eslint-disable-next-line react-hooks/exhaustive-deps
  const debouncedChangeHandler = useCallback(debounce(handleChange, INPUT_DEBOUNCE), []);
  const placeholderTextColor =
    activeThemeMode === 'dark' ? COLOR_VALUES.dark['grey-08'] : COLOR_VALUES.light['grey-08'];
  return (
    <>
      <TextInput
        ref={richRef}
        onBlur={handleChange}
        onChangeText={debouncedChangeHandler}
        multiline={true}
        flex={1}
        color={placeholderTextColor}
        placeholder={placeholder}
        placeholderTextColor={placeholderTextColor}
        flexWrap="wrap"
        key={segmentId}
      >
        {strings.map(({ id, style, value }) => {
          return (
            <Text
              key={id}
              variant="body"
              backgroundColor={style?.codeStyle ? 'base-01' : 'transparent'}
              fontStyle={style?.italics ? 'italic' : 'normal'}
              fontWeight={style?.bold ? 'bold' : 'normal'}
              style={{
                textDecorationLine: getTextDecoration(style),
              }}
            >
              {value}
            </Text>
          );
        })}
      </TextInput>
    </>
  );
};
