"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.usePollPostComposerContext = exports.durationOptions = exports.default = exports.androidDurationOptions = void 0;
var _react = require("react");
var _reactNative = require("react-native");
var _styles = require("./styles");
var _tsSdkReactNative = require("@amityco/ts-sdk-react-native");
var _community = require("../../../../core/legacy/community");
var _useAuth = _interopRequireDefault(require("../../../../core/hooks/useAuth"));
var _reactNativeSafeAreaContext = require("react-native-safe-area-context");
var _native = require("@react-navigation/native");
var _dayjs = _interopRequireDefault(require("dayjs"));
var _bottomSheet = _interopRequireDefault(require("@devvie/bottom-sheet"));
var _globalfeedSlice = _interopRequireDefault(require("../../../../core/stores/slices/globalfeedSlice"));
var _toastSlice = require("../../../../core/stores/slices/toastSlice");
var _constants = require("../../../../core/constants");
var _PollHeader = require("./components/PollHeader");
var _PollQuestion = require("./components/PollQuestion");
var _PollOptions = require("./components/PollOptions");
var _PollSelection = require("./components/PollSelection");
var _PollDuration = require("./components/PollDuration");
var _PollDurationBottomSheet = require("./components/PollDurationBottomSheet");
var _reactNativeControlledMentions = require("react-native-controlled-mentions");
var _useMention = _interopRequireDefault(require("../../../hooks/useMention"));
var _store = require("../../../../core/stores/store");
function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }
const durationOptions = exports.durationOptions = [{
  value: 1,
  label: '1 day'
}, {
  value: 3,
  label: '3 days'
}, {
  value: 7,
  label: '7 days'
}, {
  value: 14,
  label: '14 days'
}, {
  value: 30,
  label: '30 days'
}];
const androidDurationOptions = exports.androidDurationOptions = [...durationOptions, {
  value: 0,
  label: 'Custom end date'
}];
const PollPostComposerContext = /*#__PURE__*/(0, _react.createContext)(null);
const usePollPostComposerContext = () => {
  const context = (0, _react.useContext)(PollPostComposerContext);
  return context;
};
exports.usePollPostComposerContext = usePollPostComposerContext;
const AmityPollPostComposerPage = () => {
  const [loading, setLoading] = (0, _react.useState)(false);
  const [isMultipleOption, setIsMultipleOption] = (0, _react.useState)(false);
  const [pollOptions, setPollOptions] = (0, _react.useState)([{
    data: '',
    dataType: 'text'
  }, {
    data: '',
    dataType: 'text'
  }]);
  const [duration, setDuration] = (0, _react.useState)(durationOptions[durationOptions.length - 1]);
  const bottomSheetRef = (0, _react.useRef)(null);
  const [isShowingDatePicker, setIsShowingDatePicker] = (0, _react.useState)(false);
  const [isTimePickerShown, setIsTimePickerShown] = (0, _react.useState)(false);
  const [selectedDate, setSelectedDate] = (0, _react.useState)((0, _dayjs.default)().toDate());
  const [selectedTime, setSelectedTime] = (0, _react.useState)((0, _dayjs.default)().toDate());
  const [pollQuestion, setPollQuestion] = (0, _react.useState)('');
  const [mentionUsers, setMentionUsers] = (0, _react.useState)([]);
  const [mentionPosition, setMentionPosition] = (0, _react.useState)([]);
  return /*#__PURE__*/React.createElement(PollPostComposerContext.Provider, {
    value: {
      loading,
      setLoading,
      isMultipleOption,
      setIsMultipleOption,
      pollOptions,
      setPollOptions,
      pollQuestion,
      setPollQuestion,
      mentionUsers,
      setMentionUsers,
      mentionPosition,
      setMentionPosition,
      duration,
      setDuration,
      bottomSheetRef,
      isShowingDatePicker,
      setIsShowingDatePicker,
      isTimePickerShown,
      setIsTimePickerShown,
      selectedDate,
      setSelectedDate,
      selectedTime,
      setSelectedTime
    }
  }, /*#__PURE__*/React.createElement(PollPostComposer, null));
};
var _default = exports.default = AmityPollPostComposerPage;
const PollPostComposer = () => {
  const dispatch = (0, _store.useUIKitDispatch)();
  const {
    styles
  } = (0, _styles.useStyles)();
  const {
    apiRegion,
    client
  } = (0, _useAuth.default)();
  const {
    addPostToGlobalFeed
  } = _globalfeedSlice.default.actions;
  const {
    showToast,
    hideToast
  } = (0, _toastSlice.useToast)();
  const navigation = (0, _native.useNavigation)();
  const route = (0, _native.useRoute)();
  const {
    loading,
    setLoading,
    duration,
    isMultipleOption,
    setPollQuestion,
    pollOptions,
    setPollOptions,
    pollQuestion,
    mentionUsers,
    setMentionUsers,
    mentionPosition,
    setMentionPosition,
    bottomSheetRef,
    selectedTime,
    isShowingDatePicker,
    selectedDate
  } = usePollPostComposerContext();
  const {
    targetId,
    targetType,
    targetName,
    community,
    pop
  } = route.params;
  const privateCommunityId = targetType === 'community' && !(community !== null && community !== void 0 && community.isPublic) && targetId;
  const {
    renderInput,
    renderSuggestions
  } = (0, _useMention.default)({
    value: pollQuestion,
    onChange: setPollQuestion,
    communityId: privateCommunityId,
    setMentionUsers: user => {
      setMentionUsers(prev => [...prev, user]);
    },
    setMentionPosition: position => {
      setMentionPosition(prev => [...prev, position]);
    }
  });
  const goBack = () => {
    const unsavedChanges = pollQuestion.length > 0 || pollOptions.some(option => {
      var _option$data;
      return ((_option$data = option.data) === null || _option$data === void 0 ? void 0 : _option$data.trim().length) > 0;
    });
    !unsavedChanges ? navigation.goBack() : _reactNative.Alert.alert('Discard this post?', 'The post will be permanently deleted. It cannot be undone.', [{
      text: 'Keep editing',
      style: 'default'
    }, {
      text: 'Discard',
      style: 'destructive',
      onPress: navigation.goBack
    }]);
  };
  const onSuccess = () => {
    pop ? navigation.pop(pop) : navigation.goBack();
  };
  const handleCreatePost = async () => {
    try {
      setLoading(true);
      showToast({
        message: 'Creating poll...',
        type: 'loading'
      });
      const closedIn = duration.value === 0 ? _reactNative.Platform.OS === 'android' ? (0, _dayjs.default)(selectedDate).hour((0, _dayjs.default)(selectedTime).hour()).minute((0, _dayjs.default)(selectedTime).minute()).second((0, _dayjs.default)(selectedTime).second()).millisecond(0).diff((0, _dayjs.default)(), 'milliseconds') : (0, _dayjs.default)(selectedDate).diff((0, _dayjs.default)(), 'milliseconds') : duration.value * _constants.DAY;
      const answerType = isMultipleOption ? 'multiple' : 'single';
      const {
        data: {
          pollId
        }
      } = await _tsSdkReactNative.PollRepository.createPoll({
        question: pollQuestion,
        answerType: answerType,
        answers: pollOptions.filter(option => option.data.trim().length > 0),
        closedIn
      });
      const mentionees = [{
        type: 'user',
        userIds: mentionUsers.map(user => user.id)
      }];

      // TODO: share logic for admin approval
      const response = await _tsSdkReactNative.PostRepository.createPost({
        dataType: 'poll',
        targetType,
        targetId,
        data: {
          pollId,
          text: (0, _reactNativeControlledMentions.replaceTriggerValues)(pollQuestion, ({
            name
          }) => `@${name}`)
        },
        mentionees,
        metadata: {
          mentioned: mentionPosition
        }
      });
      dispatch(addPostToGlobalFeed(response.data));
      hideToast();
      if ((community === null || community === void 0 ? void 0 : community.postSetting) !== 'ADMIN_REVIEW_POST_REQUIRED') {
        return onSuccess();
      }
      const res = await (0, _community.checkCommunityPermission)(targetId, client, apiRegion);
      if (res.permissions.length > 0 && res.permissions.includes('Post/ManagePosts')) {
        return onSuccess();
      }
      onSuccess();
      _reactNative.Alert.alert('Posts sent for review', 'Your post has been submitted to the pending list. It will be published once approved by the community moderator.', [{
        text: 'OK'
      }]);
    } catch (error) {
      if (error.message.includes(_constants.text_contain_blocked_word)) {
        return _reactNative.Alert.alert('', _constants.text_contain_blocked_word);
      }
      showToast({
        type: 'failed',
        message: 'Failed to create poll. Please try again.'
      });
    } finally {
      setLoading(false);
    }
  };
  const onPressAddOption = () => {
    if (pollOptions.length < 10) {
      setPollOptions(prev => [...prev, {
        data: '',
        dataType: 'text'
      }]);
    }
  };
  const onPressRemoveOption = index => {
    const currentOptions = pollOptions.filter((_, i) => i !== index);
    setPollOptions(currentOptions);
  };
  const onChangeOptionText = (text, index) => {
    setPollOptions(prev => {
      return prev.map((item, i) => {
        if (i === index) return {
          data: text,
          dataType: 'text'
        };
        return item;
      });
    });
  };
  const isBtnDisable = loading || pollQuestion.length === 0 || pollOptions.length < 2 || pollOptions.filter(option => option.data.trim().length > 0).length < 2 || pollOptions.some(option => option.data.length > _constants.MAX_POLL_ANSWER_LENGTH);
  return /*#__PURE__*/React.createElement(_reactNativeSafeAreaContext.SafeAreaView, {
    style: styles.container,
    edges: ['top']
  }, /*#__PURE__*/React.createElement(_PollHeader.PollHeader, {
    goBack: goBack,
    targetName: targetName,
    isBtnDisable: isBtnDisable,
    handleCreatePost: handleCreatePost
  }), /*#__PURE__*/React.createElement(_reactNative.KeyboardAvoidingView, {
    style: styles.fillSpace
  }, /*#__PURE__*/React.createElement(_reactNative.ScrollView, {
    contentContainerStyle: styles.form,
    showsVerticalScrollIndicator: true
  }, /*#__PURE__*/React.createElement(_PollQuestion.PollQuestion, {
    renderInput: renderInput
  }), /*#__PURE__*/React.createElement(_PollOptions.PollOptions, {
    onPressAddOption: onPressAddOption,
    onChangeOptionText: onChangeOptionText,
    onPressRemoveOption: onPressRemoveOption
  }), /*#__PURE__*/React.createElement(_reactNative.View, {
    style: styles.divider
  }), /*#__PURE__*/React.createElement(_PollSelection.PollSelection, null), /*#__PURE__*/React.createElement(_reactNative.View, {
    style: styles.divider
  }), /*#__PURE__*/React.createElement(_PollDuration.PollDuration, null)), renderSuggestions({
    type: 'post'
  })), /*#__PURE__*/React.createElement(_bottomSheet.default, {
    ref: bottomSheetRef,
    style: styles.bottomSheet,
    height: _reactNative.Platform.OS === 'ios' && isShowingDatePicker && 600 || 400,
    disableBodyPanning: _reactNative.Platform.OS === 'android'
  }, _reactNative.Platform.OS === 'android' && /*#__PURE__*/React.createElement(_PollDurationBottomSheet.AndroidBottomSheet, null), _reactNative.Platform.OS === 'ios' && /*#__PURE__*/React.createElement(_PollDurationBottomSheet.IOSBottomSheet, null)));
};
//# sourceMappingURL=PollPostComposer.js.map