import { createContext, useContext, useRef, useState } from 'react';
import { View, ScrollView, Alert, Platform, KeyboardAvoidingView } from 'react-native';
import { useStyles } from './styles';
import { PollRepository, PostRepository } from '@amityco/ts-sdk-react-native';
import { checkCommunityPermission } from '../../../../core/legacy/community';
import useAuth from '../../../../core/hooks/useAuth';
import { SafeAreaView } from 'react-native-safe-area-context';
import { useNavigation, useRoute } from '@react-navigation/native';
import dayjs from 'dayjs';
import BottomSheet from '@devvie/bottom-sheet';
import globalFeedSlice from '../../../../core/stores/slices/globalfeedSlice';
import { useToast } from '../../../../core/stores/slices/toastSlice';
import { DAY, MAX_POLL_ANSWER_LENGTH, text_contain_blocked_word } from '../../../../core/constants';
import { PollHeader } from './components/PollHeader';
import { PollQuestion } from './components/PollQuestion';
import { PollOptions } from './components/PollOptions';
import { PollSelection } from './components/PollSelection';
import { PollDuration } from './components/PollDuration';
import { AndroidBottomSheet, IOSBottomSheet } from './components/PollDurationBottomSheet';
import { replaceTriggerValues } from 'react-native-controlled-mentions';
import useMention from '../../../hooks/useMention';
import { useUIKitDispatch } from '../../../../core/stores/store';
export const 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'
}];
export const androidDurationOptions = [...durationOptions, {
  value: 0,
  label: 'Custom end date'
}];
const PollPostComposerContext = /*#__PURE__*/createContext(null);
export const usePollPostComposerContext = () => {
  const context = useContext(PollPostComposerContext);
  return context;
};
const AmityPollPostComposerPage = () => {
  const [loading, setLoading] = useState(false);
  const [isMultipleOption, setIsMultipleOption] = useState(false);
  const [pollOptions, setPollOptions] = useState([{
    data: '',
    dataType: 'text'
  }, {
    data: '',
    dataType: 'text'
  }]);
  const [duration, setDuration] = useState(durationOptions[durationOptions.length - 1]);
  const bottomSheetRef = useRef(null);
  const [isShowingDatePicker, setIsShowingDatePicker] = useState(false);
  const [isTimePickerShown, setIsTimePickerShown] = useState(false);
  const [selectedDate, setSelectedDate] = useState(dayjs().toDate());
  const [selectedTime, setSelectedTime] = useState(dayjs().toDate());
  const [pollQuestion, setPollQuestion] = useState('');
  const [mentionUsers, setMentionUsers] = useState([]);
  const [mentionPosition, setMentionPosition] = 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));
};
export default AmityPollPostComposerPage;
const PollPostComposer = () => {
  const dispatch = useUIKitDispatch();
  const {
    styles
  } = useStyles();
  const {
    apiRegion,
    client
  } = useAuth();
  const {
    addPostToGlobalFeed
  } = globalFeedSlice.actions;
  const {
    showToast,
    hideToast
  } = useToast();
  const navigation = useNavigation();
  const route = 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
  } = useMention({
    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() : 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 ? Platform.OS === 'android' ? dayjs(selectedDate).hour(dayjs(selectedTime).hour()).minute(dayjs(selectedTime).minute()).second(dayjs(selectedTime).second()).millisecond(0).diff(dayjs(), 'milliseconds') : dayjs(selectedDate).diff(dayjs(), 'milliseconds') : duration.value * DAY;
      const answerType = isMultipleOption ? 'multiple' : 'single';
      const {
        data: {
          pollId
        }
      } = await 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 PostRepository.createPost({
        dataType: 'poll',
        targetType,
        targetId,
        data: {
          pollId,
          text: 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 checkCommunityPermission(targetId, client, apiRegion);
      if (res.permissions.length > 0 && res.permissions.includes('Post/ManagePosts')) {
        return onSuccess();
      }
      onSuccess();
      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(text_contain_blocked_word)) {
        return Alert.alert('', 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 > MAX_POLL_ANSWER_LENGTH);
  return /*#__PURE__*/React.createElement(SafeAreaView, {
    style: styles.container,
    edges: ['top']
  }, /*#__PURE__*/React.createElement(PollHeader, {
    goBack: goBack,
    targetName: targetName,
    isBtnDisable: isBtnDisable,
    handleCreatePost: handleCreatePost
  }), /*#__PURE__*/React.createElement(KeyboardAvoidingView, {
    style: styles.fillSpace
  }, /*#__PURE__*/React.createElement(ScrollView, {
    contentContainerStyle: styles.form,
    showsVerticalScrollIndicator: true
  }, /*#__PURE__*/React.createElement(PollQuestion, {
    renderInput: renderInput
  }), /*#__PURE__*/React.createElement(PollOptions, {
    onPressAddOption: onPressAddOption,
    onChangeOptionText: onChangeOptionText,
    onPressRemoveOption: onPressRemoveOption
  }), /*#__PURE__*/React.createElement(View, {
    style: styles.divider
  }), /*#__PURE__*/React.createElement(PollSelection, null), /*#__PURE__*/React.createElement(View, {
    style: styles.divider
  }), /*#__PURE__*/React.createElement(PollDuration, null)), renderSuggestions({
    type: 'post'
  })), /*#__PURE__*/React.createElement(BottomSheet, {
    ref: bottomSheetRef,
    style: styles.bottomSheet,
    height: Platform.OS === 'ios' && isShowingDatePicker && 600 || 400,
    disableBodyPanning: Platform.OS === 'android'
  }, Platform.OS === 'android' && /*#__PURE__*/React.createElement(AndroidBottomSheet, null), Platform.OS === 'ios' && /*#__PURE__*/React.createElement(IOSBottomSheet, null)));
};
//# sourceMappingURL=PollPostComposer.js.map