import React from 'react';
import {StyleProp, Text, TextStyle} from 'react-native';
import {
  isMentionPartType,
  parseValue,
  Part,
  PartType,
} from 'react-native-controlled-mentions';
import TaggTypeahead from '../components/common/TaggTypeahead';
import {TAGG_LIGHT_BLUE} from '../constants';
import {UserType} from '../types';

/**
 * Part renderer
 *
 * https://github.com/dabakovich/react-native-controlled-mentions#rendering-mentioninputs-value
 */
const renderPart = (
  part: Part,
  index: number,
  handlePress: (user: UserType) => void,
) => {
  // Just plain text
  if (!part.partType) {
    return <Text key={index}>{part.text}</Text>;
  }

  // Mention type part
  if (isMentionPartType(part.partType)) {
    return (
      <Text
        key={`${index}-${part.data?.trigger}`}
        style={part.partType.textStyle}
        onPress={() => {
          if (part.data) {
            handlePress({
              userId: part.data.id,
              username: part.data.name,
            });
          }
        }}>
        {part.text}
      </Text>
    );
  }

  // Other styled part types
  return (
    <Text key={`${index}-pattern`} style={part.partType.textStyle}>
      {part.text}
    </Text>
  );
};

interface RenderProps {
  value: string;
  styles: StyleProp<TextStyle>;
  onPress: (user: UserType) => void;
}

/**
 * Value renderer. Parsing value to parts array and then mapping the array using 'renderPart'
 *
 * https://github.com/dabakovich/react-native-controlled-mentions#rendering-mentioninputs-value
 */
export const renderTextWithMentions: React.FC<RenderProps> = ({
  value,
  styles,
  onPress,
}) => {
  const {parts} = parseValue(value, mentionPartTypes);
  return (
    <Text style={styles}>
      {parts.map((part, index) => renderPart(part, index, onPress))}
    </Text>
  );
};

export const mentionPartTypes: PartType[] = [
  {
    trigger: '@',
    renderSuggestions: (props) => <TaggTypeahead {...props} />,
    allowedSpacesCount: 0,
    isInsertSpaceAfterMention: true,
    textStyle: {color: TAGG_LIGHT_BLUE},
  },
];
