import { useCallback, useEffect, useState } from 'react';
import { TouchableOpacity, View, Text, Modal, KeyboardAvoidingView, Platform, ScrollView } from 'react-native';
import { SvgXml } from 'react-native-svg';
import { closeIcon } from '../../../../core/assets/icons/xml';
import { useStyles } from './styles';
import { editComment } from '../../../../core/legacy/comment';
import { useTheme } from 'react-native-paper';
import { CommunityRepository, UserRepository } from '@amityco/ts-sdk-react-native';
import useMention from '../../../hooks/useMention';
import { replaceTriggerValues } from 'react-native-controlled-mentions';
const EditCommentModal = ({
  visible,
  onClose,
  commentDetail,
  onFinishEdit
}) => {
  var _commentDetail$data, _commentDetail$data2, _commentDetail$data4;
  const theme = useTheme();
  const styles = useStyles();
  const [inputMessage, setInputMessage] = useState((commentDetail === null || commentDetail === void 0 || (_commentDetail$data = commentDetail.data) === null || _commentDetail$data === void 0 ? void 0 : _commentDetail$data.text) ?? '');
  const [mentionUsers, setMentionUsers] = useState([]);
  const [mentionsPosition, setMentionsPosition] = useState([]);
  const [privateCommunityId, setPrivateCommunityId] = useState(null);
  const {
    renderInput,
    renderSuggestions
  } = useMention({
    value: inputMessage,
    communityId: privateCommunityId,
    onChange: setInputMessage,
    setMentionUsers: user => {
      setMentionUsers(prev => [...prev, user]);
    },
    setMentionPosition: position => {
      setMentionsPosition(prev => [...prev, position]);
    }
  });
  const handleEditComment = async () => {
    if (inputMessage) {
      const comment = replaceTriggerValues(inputMessage, ({
        name
      }) => `@${name}`);
      const mentionedUserIds = mentionUsers.map(user => user.userId);
      const editedComment = await editComment(comment, commentDetail.commentId, 'post', mentionedUserIds, mentionsPosition);
      if (editedComment) {
        var _editedComment$data;
        onFinishEdit && onFinishEdit(editedComment === null || editedComment === void 0 || (_editedComment$data = editedComment.data) === null || _editedComment$data === void 0 ? void 0 : _editedComment$data.text);
      }
    }
  };
  const disabledState = !inputMessage || inputMessage === (commentDetail === null || commentDetail === void 0 || (_commentDetail$data2 = commentDetail.data) === null || _commentDetail$data2 === void 0 ? void 0 : _commentDetail$data2.text);
  const disabledColor = disabledState && {
    color: theme.colors.baseShade2
  };
  const parsePostText = useCallback((text, mentionUsersArr) => {
    const parsedText = text.replace(/@([\w\s-]+)/g, (_, username) => {
      const mentionee = mentionUsersArr.find(user => user.displayName === username);
      const mentioneeId = mentionee ? mentionee.userId : '';
      return `{@}[${username}](${mentioneeId})`;
    });
    return parsedText;
  }, []);
  const getMentionPositions = useCallback((text, mentioneeIds) => {
    let index = 0;
    let mentions = [];
    let match;
    const mentionRegex = /@([\w-]+)/g;
    while ((match = mentionRegex.exec(text)) !== null) {
      let username = match[1];
      let mentioneeId = mentioneeIds[index++];
      let startIdx = match.index;
      let mention = {
        type: 'user',
        displayName: username,
        index: startIdx,
        length: match[0].length,
        userId: mentioneeId
      };
      mentions.push(mention);
    }
    return mentions;
  }, []);
  const getMentionUsers = useCallback(async mentionIds => {
    var _commentDetail$data3;
    const {
      data
    } = await UserRepository.getUserByIds(mentionIds);
    const users = data.map(user => {
      return {
        ...user,
        name: user.displayName,
        id: user.userId
      };
    });
    setMentionUsers(users);
    const parsedText = parsePostText((commentDetail === null || commentDetail === void 0 || (_commentDetail$data3 = commentDetail.data) === null || _commentDetail$data3 === void 0 ? void 0 : _commentDetail$data3.text) ?? '', users);
    setInputMessage(parsedText);
    return users;
  }, [parsePostText, commentDetail === null || commentDetail === void 0 || (_commentDetail$data4 = commentDetail.data) === null || _commentDetail$data4 === void 0 ? void 0 : _commentDetail$data4.text]);
  useEffect(() => {
    if (visible) {
      var _commentDetail$mentio;
      if ((commentDetail === null || commentDetail === void 0 || (_commentDetail$mentio = commentDetail.mentionPosition) === null || _commentDetail$mentio === void 0 ? void 0 : _commentDetail$mentio.length) > 0) {
        var _commentDetail$data5;
        const mentionPositions = getMentionPositions((commentDetail === null || commentDetail === void 0 || (_commentDetail$data5 = commentDetail.data) === null || _commentDetail$data5 === void 0 ? void 0 : _commentDetail$data5.text) ?? '', commentDetail.mentionPosition.map(position => position.userId) ?? []);
        getMentionUsers(commentDetail.mentionPosition.map(position => position.userId) ?? []);
        setMentionsPosition(mentionPositions);
      } else {
        var _commentDetail$data6;
        setInputMessage((commentDetail === null || commentDetail === void 0 || (_commentDetail$data6 = commentDetail.data) === null || _commentDetail$data6 === void 0 ? void 0 : _commentDetail$data6.text) ?? '');
      }
    }
  }, [getMentionPositions, getMentionUsers, commentDetail, visible]);
  useEffect(() => {
    if ((commentDetail === null || commentDetail === void 0 ? void 0 : commentDetail.targetType) === 'community' && visible) {
      CommunityRepository.getCommunity(commentDetail === null || commentDetail === void 0 ? void 0 : commentDetail.targetId, ({
        error,
        data,
        loading
      }) => {
        if (!error && !loading) {
          !data.isPublic && setPrivateCommunityId(data.communityId);
        }
      });
    }
    return () => {};
  }, [commentDetail === null || commentDetail === void 0 ? void 0 : commentDetail.targetId, commentDetail === null || commentDetail === void 0 ? void 0 : commentDetail.targetType, visible]);
  return /*#__PURE__*/React.createElement(Modal, {
    visible: visible,
    animationType: "slide"
  }, /*#__PURE__*/React.createElement(View, {
    style: styles.header
  }, /*#__PURE__*/React.createElement(TouchableOpacity, {
    style: styles.closeButton,
    onPress: onClose
  }, /*#__PURE__*/React.createElement(SvgXml, {
    xml: closeIcon(theme.colors.base),
    width: "17",
    height: "17"
  })), /*#__PURE__*/React.createElement(View, {
    style: styles.headerTextContainer
  }, /*#__PURE__*/React.createElement(Text, {
    style: styles.headerText
  }, "Edit Comment")), /*#__PURE__*/React.createElement(TouchableOpacity, {
    onPress: handleEditComment,
    style: styles.headerTextContainer,
    disabled: disabledState
  }, /*#__PURE__*/React.createElement(Text, {
    style: [styles.headerText, disabledColor]
  }, "Save"))), /*#__PURE__*/React.createElement(KeyboardAvoidingView, {
    behavior: Platform.OS === 'ios' ? 'padding' : 'height',
    keyboardVerticalOffset: Platform.select({
      ios: 100,
      android: 80
    }),
    style: styles.AllInputWrap
  }, /*#__PURE__*/React.createElement(View, {
    style: styles.container
  }, /*#__PURE__*/React.createElement(View, {
    style: styles.AllInputWrap
  }, /*#__PURE__*/React.createElement(ScrollView, {
    style: styles.container
  }, renderInput({
    multiline: true,
    placeholder: 'What are you thinking...',
    placeholderTextColor: theme.colors.baseShade3
  })))), renderSuggestions({
    type: 'post'
  })));
};
export default EditCommentModal;
//# sourceMappingURL=index.js.map