import React from 'react';
import {Text} 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';

/**
 * Part renderer
 *
 * https://github.com/dabakovich/react-native-controlled-mentions#rendering-mentioninputs-value
 *
 * @param part
 * @param index
 */
const renderPart = (part: Part, index: number) => {
  // 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={() => console.log('Pressed', part.data)}>
        {part.text}
      </Text>
    );
  }

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

/**
 * 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
 *
 * @param value - value from MentionInput
 * @param partTypes - the part types array that you providing to MentionInput
 */
export const renderValue: React.FC = (value: string, partTypes: PartType[]) => {
  const {parts} = parseValue(value, partTypes);
  return <Text>{parts.map(renderPart)}</Text>;
};

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