import { memo, useCallback, useState } from 'react';
import { ActivityIndicator, Alert, KeyboardAvoidingView, Platform, Text, TextInput, TouchableOpacity, View } from 'react-native';
import Modal from 'react-native-modalbox';
import { useTheme } from 'react-native-paper';
import { useStyles } from '../styles';
import useConfig from '../../../../hooks/useConfig';
import { ComponentID, ElementID, PageID } from '../../../../enums';
import { checkURLValidation } from '../../../../../core/utils/url';
import useAuth from '../../../../../core/hooks/useAuth';
import { SvgXml } from 'react-native-svg';
import { storyDraftDeletHyperLink } from '../../../../../core/assets/icons/xml';
const HyperlinkConfig = ({
  isVisibleModal,
  onHyperLinkSubmit,
  setIsVisibleModal,
  hyperlinkItem
}) => {
  var _getUiKitConfig;
  const styles = useStyles();
  const theme = useTheme();
  const {
    getUiKitConfig
  } = useConfig();
  const [url, setUrl] = useState((hyperlinkItem === null || hyperlinkItem === void 0 ? void 0 : hyperlinkItem.url) ?? '');
  const {
    client
  } = useAuth();
  const [customizedText, setCustomizedText] = useState((hyperlinkItem === null || hyperlinkItem === void 0 ? void 0 : hyperlinkItem.customText) ?? '');
  const [loading, setLoading] = useState(false);
  const [urlErrorMessage, setUrlErrorMessage] = useState(null);
  const [customTextErrorMessage, setCustomTextErrorMessage] = useState(null);
  const invalidURLText = 'Please enter a valid URL.';
  const blockedURLText = 'Please enter a whitelisted URL.';
  const blockedCustomText = 'Your text contains a blocklisted word.';
  const configDoneText = ((_getUiKitConfig = getUiKitConfig({
    page: PageID.StoryPage,
    component: ComponentID.HyperLinkConfig,
    element: ElementID.DoneBtn
  })) === null || _getUiKitConfig === void 0 ? void 0 : _getUiKitConfig.done_button_text) ?? 'Done';
  const reset = useCallback(() => {
    setUrl('');
    setCustomizedText('');
  }, []);
  const onClosed = useCallback(() => {
    setIsVisibleModal(false);
  }, [setIsVisibleModal]);
  const handleCancel = useCallback(() => {
    const hasChanges = url !== ((hyperlinkItem === null || hyperlinkItem === void 0 ? void 0 : hyperlinkItem.url) ?? '') || customizedText !== ((hyperlinkItem === null || hyperlinkItem === void 0 ? void 0 : hyperlinkItem.customText) ?? '');
    if (hasChanges) {
      Alert.alert('Unsaved changes', "Are you sure you want to cancel? Your changes won't be saved.", [{
        text: 'No',
        style: 'cancel'
      }, {
        text: 'Yes',
        style: 'destructive',
        onPress: () => {
          if (hyperlinkItem) {
            setUrl(hyperlinkItem.url);
            setCustomizedText(hyperlinkItem.customText);
          } else {
            reset();
          }
          setUrlErrorMessage(null);
          setCustomTextErrorMessage(null);
          onClosed();
        }
      }]);
    } else {
      onClosed();
    }
  }, [url, customizedText, hyperlinkItem, onClosed, reset]);
  const handleUrl = useCallback(text => {
    setUrlErrorMessage(null);
    setUrl(text);
    const isValid = checkURLValidation(text);
    !isValid && setUrlErrorMessage(invalidURLText);
  }, []);
  const handleCustomText = useCallback(text => {
    setCustomTextErrorMessage(null);
    setCustomizedText(text);
  }, []);
  const validateHyperlinkUrl = useCallback(async () => {
    if (url.length > 0) {
      const validatedUrl = await client.validateUrls([url]).catch(() => false);
      !validatedUrl && setUrlErrorMessage(blockedURLText);
      return validatedUrl;
    }
    return false;
  }, [client, url]);
  const validateHyperlinkText = useCallback(async () => {
    if (customizedText.length > 0) {
      const validatedCustomText = await client.validateTexts([customizedText]).catch(() => false);
      !validatedCustomText && setCustomTextErrorMessage(blockedCustomText);
      return validatedCustomText;
    }
    return true;
  }, [client, customizedText]);
  const validateHyperlink = useCallback(async () => {
    const validUrl = await validateHyperlinkUrl();
    const validText = await validateHyperlinkText();
    validUrl && validText && onHyperLinkSubmit({
      url,
      customText: customizedText
    });
  }, [customizedText, onHyperLinkSubmit, url, validateHyperlinkText, validateHyperlinkUrl]);
  const onSubmit = useCallback(async () => {
    setLoading(true);
    await validateHyperlink();
    setLoading(false);
  }, [validateHyperlink]);
  const onDeleteHyperlink = useCallback(() => {
    reset();
    onHyperLinkSubmit();
  }, [onHyperLinkSubmit, reset]);
  const onPressDeleteHyperlink = useCallback(() => {
    Alert.alert('Remove link?', 'This link will be removed from story', [{
      text: 'Cancel'
    }, {
      text: 'Remove',
      onPress: onDeleteHyperlink,
      style: 'destructive'
    }]);
  }, [onDeleteHyperlink]);
  return /*#__PURE__*/React.createElement(Modal, {
    style: styles.bottomSheet,
    isOpen: isVisibleModal,
    onClosed: onClosed,
    position: "bottom",
    swipeToClose: true,
    swipeArea: 250,
    backButtonClose: true,
    coverScreen: true
  }, /*#__PURE__*/React.createElement(KeyboardAvoidingView, {
    behavior: Platform.OS === 'ios' ? 'padding' : 'height',
    style: styles.commentBottomSheet
  }, /*#__PURE__*/React.createElement(View, {
    style: styles.handleBar
  }), /*#__PURE__*/React.createElement(View, {
    style: styles.titleContainer
  }, /*#__PURE__*/React.createElement(View, {
    style: styles.flexContainer
  }, /*#__PURE__*/React.createElement(Text, {
    onPress: handleCancel,
    style: styles.cancel
  }, "Cancel")), /*#__PURE__*/React.createElement(View, {
    style: styles.flexContainer
  }, /*#__PURE__*/React.createElement(Text, {
    style: styles.title
  }, "Add link")), /*#__PURE__*/React.createElement(View, {
    style: styles.flexContainer
  }, /*#__PURE__*/React.createElement(Text, {
    style: [styles.done, url && !urlErrorMessage && !customTextErrorMessage && styles.activeDone],
    disabled: !url || !!urlErrorMessage || !!customTextErrorMessage,
    onPress: onSubmit
  }, configDoneText))), /*#__PURE__*/React.createElement(View, {
    style: styles.horizontalSperator
  }), loading && /*#__PURE__*/React.createElement(ActivityIndicator, {
    animating: loading,
    size: "small",
    color: theme.colors.base
  }), /*#__PURE__*/React.createElement(View, {
    style: styles.contentContainer
  }, /*#__PURE__*/React.createElement(View, {
    style: [styles.inputContainer, url.length > 0 && urlErrorMessage && styles.alertBorderColor]
  }, /*#__PURE__*/React.createElement(Text, {
    style: styles.label
  }, "URL ", /*#__PURE__*/React.createElement(Text, {
    style: styles.requiredSign
  }, "*")), /*#__PURE__*/React.createElement(TextInput, {
    defaultValue: url,
    onChangeText: handleUrl,
    style: styles.input,
    placeholder: "https://www.example.com",
    placeholderTextColor: theme.colors.baseShade2,
    onFocus: validateHyperlinkText
  })), urlErrorMessage && /*#__PURE__*/React.createElement(Text, {
    style: styles.inValidUrl
  }, urlErrorMessage), /*#__PURE__*/React.createElement(View, {
    style: [styles.inputContainer, customizedText.length > 0 && customTextErrorMessage && styles.alertBorderColor]
  }, /*#__PURE__*/React.createElement(View, {
    style: styles.rowContainer
  }, /*#__PURE__*/React.createElement(Text, {
    style: styles.label
  }, "Customize Link Text"), /*#__PURE__*/React.createElement(Text, {
    style: styles.textCount
  }, customizedText.length, "/30")), /*#__PURE__*/React.createElement(TextInput, {
    defaultValue: customizedText,
    onChangeText: handleCustomText,
    style: styles.input,
    placeholder: "Name your link",
    placeholderTextColor: theme.colors.baseShade2,
    maxLength: 30,
    onFocus: validateHyperlinkUrl
  })), customTextErrorMessage ? /*#__PURE__*/React.createElement(Text, {
    style: styles.inValidUrl
  }, customTextErrorMessage) : /*#__PURE__*/React.createElement(Text, {
    style: styles.note
  }, "This Text will show on the link instead of URL."), hyperlinkItem && /*#__PURE__*/React.createElement(View, null, /*#__PURE__*/React.createElement(View, {
    style: styles.removeLinkContainer
  }), /*#__PURE__*/React.createElement(TouchableOpacity, {
    style: styles.deleteHyperlinkContainer,
    onPress: onPressDeleteHyperlink
  }, /*#__PURE__*/React.createElement(SvgXml, {
    xml: storyDraftDeletHyperLink(),
    width: "20",
    height: "20"
  }), /*#__PURE__*/React.createElement(Text, {
    style: styles.removeLink
  }, "Remove link")), /*#__PURE__*/React.createElement(View, {
    style: styles.removeLinkDivider
  })))));
};
export default /*#__PURE__*/memo(HyperlinkConfig);
//# sourceMappingURL=HyperLinkConfig.js.map