"use strict";

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = void 0;
var _react = _interopRequireWildcard(require("react"));
var _reactNative = require("react-native");
var _colors = require("./helpers/colors");
var _Matrics = _interopRequireDefault(require("./helpers/Matrics"));
var _icons = require("./helpers/icons");
var _reactNativeWebview = _interopRequireDefault(require("react-native-webview"));
var _reactNativeActionsSheet = require("react-native-actions-sheet");
var _reactNativeTrackyLib = require("react-native-tracky-lib");
var _reactRedux = require("react-redux");
var actions = _interopRequireWildcard(require("./redux/slices"));
var _reactNativeEventListeners = require("react-native-event-listeners");
var _constants = _interopRequireDefault(require("./constants"));
var _common = require("./helpers/common");
function _interopRequireDefault(e) { return e && e.__esModule ? e : { default: e }; }
function _interopRequireWildcard(e, t) { if ("function" == typeof WeakMap) var r = new WeakMap(), n = new WeakMap(); return (_interopRequireWildcard = function (e, t) { if (!t && e && e.__esModule) return e; var o, i, f = { __proto__: null, default: e }; if (null === e || "object" != typeof e && "function" != typeof e) return f; if (o = t ? n : r) { if (o.has(e)) return o.get(e); o.set(e, f); } for (const t in e) "default" !== t && {}.hasOwnProperty.call(e, t) && ((i = (o = Object.defineProperty) && Object.getOwnPropertyDescriptor(e, t)) && (i.get || i.set) ? o(f, t, i) : f[t] = e[t]); return f; })(e, t); }
function _extends() { return _extends = Object.assign ? Object.assign.bind() : function (n) { for (var e = 1; e < arguments.length; e++) { var t = arguments[e]; for (var r in t) ({}).hasOwnProperty.call(t, r) && (n[r] = t[r]); } return n; }, _extends.apply(null, arguments); } // import { globalStyles } from '../../../../src/helpers/globalStyles';
// import { API_URL, APP_MODE } from '@env';
const {
  CgmTrackyLib
} = _reactNative.NativeModules;
const ProgressWebView = props => {
  // const { url } = props; // Get the URL from the route parameters
  const {
    loading,
    isError,
    webviewRef,
    runBeforeFirst,
    setCanGoBack,
    environment,
    mobileNumber,
    uuid,
    clientSource,
    platform,
    moduleName
  } = props;
  const [activeGoodflipTab, setActiveGoodflipTab] = (0, _react.useState)('GoodflipProgressAchieveSectionScreen');
  const baseUrl = environment.toUpperCase() === 'PROD' ? _constants.default.PROD_BASE_URL : _constants.default.STAGE_BASE_URL;
  const goodflipUrl = environment.toUpperCase() === 'PROD' ? _constants.default.PROD_GOODFLIP_URL : _constants.default.STAG_GOODFLIP_URL;
  const appGoodflipUrl = environment.toUpperCase() === 'PROD' ? _constants.default.PROD_APP_GOODFLIP_URL : _constants.default.STAG_APP_GOODFLIP_URL;
  const dispatch = (0, _reactRedux.useDispatch)();
  const {
    user
  } = (0, _reactRedux.useSelector)(state => state.Auth);
  const [url, setUrl] = (0, _react.useState)('');
  const [isLoading, setIsLoading] = (0, _react.useState)(false);
  const [hasError, setHasError] = (0, _react.useState)(false);
  const [isFreeUser, setIsFreeUser] = (0, _react.useState)(false);
  (0, _react.useEffect)(() => {
    var _user$data;
    setIsFreeUser((user === null || user === void 0 || (_user$data = user.data) === null || _user$data === void 0 || (_user$data = _user$data.paidUser) === null || _user$data === void 0 ? void 0 : _user$data.toString()) !== '1');
  }, [user]);
  const getAchieveUrl = () => {
    var _user$data2, _user$data3, _user$data4;
    return isFreeUser ? encodeURIComponent(JSON.stringify({
      uuid: '',
      mobileNumber: mobileNumber,
      moduleName: 'locked-progress',
      environment: environment,
      clientSource: clientSource,
      name: user === null || user === void 0 || (_user$data2 = user.data) === null || _user$data2 === void 0 ? void 0 : _user$data2.name
    })) : encodeURIComponent(JSON.stringify({
      uuid: '',
      mobileNumber: mobileNumber,
      moduleName: 'achieve',
      environment: environment,
      clientSource: clientSource,
      name: user === null || user === void 0 || (_user$data3 = user.data) === null || _user$data3 === void 0 ? void 0 : _user$data3.name,
      therapyArea: (0, _common.getTherapyArea)(user === null || user === void 0 ? void 0 : user.data) || 'metabolism',
      conditionName: (0, _common.getDiseaseType)(user === null || user === void 0 ? void 0 : user.data) || 'diabetes',
      patientID: user === null || user === void 0 || (_user$data4 = user.data) === null || _user$data4 === void 0 ? void 0 : _user$data4.patient_id
    }));
  };
  const getUrl = () => {
    var _user$data5;
    return encodeURIComponent(JSON.stringify({
      uuid: uuid,
      mobileNumber: mobileNumber,
      moduleName: moduleName,
      environment: environment,
      clientSource: clientSource,
      name: user === null || user === void 0 || (_user$data5 = user.data) === null || _user$data5 === void 0 ? void 0 : _user$data5.name
    }));
  };
  (0, _react.useEffect)(() => {
    authenticateUser();
  }, []);
  const authenticateUser = () => {
    setIsLoading(true);
    const payload = uuid ? {
      uuid: uuid
    } : {
      contact_no: mobileNumber
    };
    new Promise((resolve, reject) => {
      dispatch(actions.authenticateUserRequest({
        payload,
        resolve,
        reject,
        environment: environment
      }));
    }).then(res => {
      setIsLoading(false); // API succeeded
    }).catch(error => {
      console.log('error--', error);
      console.error('Error authenticating user:', error);
      setHasError(true); // API failed
      setIsLoading(false);
    });
  };
  (0, _react.useEffect)(() => {
    if (user) {
      if (activeGoodflipTab === 'GoodflipProgressAchieveSectionScreen') {
        let achieveUrl = '';
        if (!isFreeUser) {
          achieveUrl = `${goodflipUrl}/metabolism/diabetes/achieve?data=${getAchieveUrl()}`;
        } else {
          achieveUrl = `${goodflipUrl}/locked-progress?data=${getAchieveUrl()}`;
        }
        setUrl(achieveUrl);
      } else if (activeGoodflipTab === 'GoodflipProgressVitalsSectionScreen') {
        setUrl(`${appGoodflipUrl}/progress/vitals?data=${getUrl()}`);
      } else if (activeGoodflipTab === 'GoodflipProgressDeviceSectionScreen') {
        setUrl(`${appGoodflipUrl}/progress/progress-device-section?data=${getUrl()}`);
      }
    }
  }, [activeGoodflipTab, isFreeUser]);
  const goodflipTabs = (0, _react.useMemo)(() => {
    const tabs = [{
      id: 'GoodflipProgressAchieveSectionScreen',
      title: 'Achieve',
      icon: focused => focused ? /*#__PURE__*/_react.default.createElement(_icons.Icons.AchieveIcon, {
        fill: 'black'
      }) : null,
      url: 'GoodflipProgressAchieveSectionScreen'
    }, {
      id: 'GoodflipProgressVitalsSectionScreen',
      title: 'Vitals',
      icon: focused => focused ? /*#__PURE__*/_react.default.createElement(_icons.Icons.HeartIcon, {
        fill: 'black'
      }) : null,
      url: 'GoodflipProgressVitalsSectionScreen'
    }, {
      id: 'GoodflipProgressDeviceSectionScreen',
      title: 'Devices',
      icon: focused => focused ? /*#__PURE__*/_react.default.createElement(_icons.Icons.SmartWatchIcon, {
        fill: 'black'
      }) : null,
      url: 'GoodflipProgressDeviceSectionScreen'
    }].filter(Boolean);
    return tabs;
  }, []);
  const handleMessage = async event => {
    const message = event.nativeEvent.data;
    const webviewData = JSON.parse(message);
    const {
      data,
      action
    } = webviewData;
    const {
      age,
      height,
      gender,
      dob,
      userId,
      subAction
    } = data;

    // if (action === 'updateBcaVitals') {
    //   dispatch(actions.updateBcaAndSpiromter({isBcaSpirometerChanged: true}));
    //   dispatch(
    //     actions.updateUserMetaInfoRequest({
    //       getBcaReadings: true,
    //       updateUserMetaInfo: true,
    //     }),
    //   );
    // }

    if (action === 'updateUserInfo') {
      // dispatch(
      //   actions.updateUserMetaInfoRequest({
      //     getBcaReadings: true,
      //     updateUserMetaInfo: true,
      //   }),
      // );
      // new Promise((resolve, reject) => {
      //   dispatch(
      //     actions.patientDetailsRequest({
      //       resolve,
      //       reject,
      //     }),
      //   );
      // });
    }
    if (action === 'init_device_bottomsheet') {
      _reactNativeActionsSheet.SheetManager.show('bca_device_list_sheet', {
        payload: {
          onPressConnectSmartScaleBtn: deviceType => {
            _reactNativeActionsSheet.SheetManager.hide('bca_device_list_sheet').then(() => {
              if ((deviceType === null || deviceType === void 0 ? void 0 : deviceType.device_type) === 'GoodFlip') {
                (0, _reactNativeTrackyLib.initializeTracky)({
                  age: Number(age),
                  gender: gender,
                  height: Number(Number(height).toFixed(0))
                });
              }
            });
          }
        }
      });
    } else if (action === 'syncDevice') {
      (0, _reactNativeTrackyLib.initializeTracky)({
        age: Number(age),
        gender: gender,
        height: Number(height)
      });
    } else if (action === 'buy_now') {
      // try {
      //   if (constantsFirebaseData && constantsFirebaseData[0]?.value) {
      //     let shopifyBcaUrl = Constants.ONCO_STORE_LINKS.shopify_bca_url;
      //     const parsedData = JSON.parse(constantsFirebaseData[0].value);
      //     if (parsedData?.shopify_bca_url) {
      //       shopifyBcaUrl = parsedData.shopify_bca_url;
      //       Navigation.navigate('WebviewScreen', {
      //         headerTitle: 'Back',
      //         url: shopifyBcaUrl,
      //       });
      //     }
      //   }
      // } catch (error) {
      //   console.log('error', error);
      // }
    }
    // else if (action === 'sharePdf') {
    //   try {
    //     const res = await ReactNativeBlobUtil.config({
    //       fileCache: true,
    //     }).fetch('GET', data?.url);
    //     const resp = await res.readFile('base64');
    //     const filename = `SmartScaleReport_${userData?.name}_${moment(
    //       data?.datetime,
    //     ).format('DDMMYYHHmmss')}`;
    //     const options: ShareOptions = {
    //       title: `${filename}.pdf`,
    //       filename: `${filename}.pdf`,
    //       url: `data:application/pdf;base64,${resp}`,
    //     };

    //     await Share.open(options);
    //   } catch (error) {
    //     if (error?.message === 'User did not share') {
    //     } else {
    //       Popup.error('File could not be generated. Please try again.');
    //     }
    //   }
    // }
  };
  console.log('icons', _icons.Icons);
  return /*#__PURE__*/_react.default.createElement(_reactNative.View, {
    style: styles.goodflipContainer
  }, !hasError && /*#__PURE__*/_react.default.createElement(_reactNative.View, {
    style: styles.tabsRow
  }, goodflipTabs.map(tab => /*#__PURE__*/_react.default.createElement(_reactNative.TouchableOpacity, {
    key: tab.id,
    style: styles.tabButton,
    onPress: () => setActiveGoodflipTab(tab.id)
  }, /*#__PURE__*/_react.default.createElement(_reactNative.View, {
    style: [styles.tabButtonInner, {
      backgroundColor: activeGoodflipTab === tab.id ? 'honeydew' : 'white'
    }]
  }, /*#__PURE__*/_react.default.createElement(_reactNative.Text, {
    style: [styles.tabButtonText, activeGoodflipTab === tab.id && styles.activeTabButtonText]
  }, tab.title)), /*#__PURE__*/_react.default.createElement(_reactNative.View, {
    style: [styles.tabBottomBar, activeGoodflipTab === tab.id && styles.activeTabBottomBar]
  })))), hasError && /*#__PURE__*/_react.default.createElement(_reactNative.View, {
    style: styles.errorContainer
  }, /*#__PURE__*/_react.default.createElement(_reactNative.Text, {
    style: styles.errorText
  }, "Something went wrong")), url && !isError && !loading && !isLoading && !hasError ? /*#__PURE__*/_react.default.createElement(_reactNativeWebview.default, _extends({
    ref: webviewRef,
    source: {
      uri: url,
      headers: {
        platform: platform
      }
    },
    onMessage: handleMessage
  }, runBeforeFirst && {
    injectedJavaScriptBeforeContentLoaded: runBeforeFirst
  }, {
    javaScriptEnabled: true,
    onError: errorMessage => {
      _reactNativeEventListeners.EventRegister.emitEvent('mytatva-event', {
        message: 'web-view-error',
        errorMessage: errorMessage
      });
    }
  })) : null);
};
var _default = exports.default = ProgressWebView;
const styles = _reactNative.StyleSheet.create({
  container: {
    flex: 1
    // backgroundColor: colors.backgroundColor,
  },
  searchContainer: {
    marginHorizontal: _Matrics.default.s(16),
    marginVertical: _Matrics.default.vs(12),
    flexDirection: 'row',
    alignItems: 'center',
    ...(_reactNative.Platform.OS === 'ios' && {
      paddingVertical: _Matrics.default.vs(12)
    }),
    paddingHorizontal: _Matrics.default.s(12),
    gap: _Matrics.default.s(8),
    // backgroundColor: colors.white,
    borderRadius: _Matrics.default.vs(12),
    borderWidth: 1
    // borderColor: colors.lightGrey,
    // ...globalStyles.shadowContainer,
  },
  row: {
    flexDirection: 'row',
    alignItems: 'center',
    gap: _Matrics.default.s(8)
  },
  toastContainer: {
    paddingVertical: _Matrics.default.vs(12),
    paddingHorizontal: _Matrics.default.s(16),
    marginHorizontal: _Matrics.default.s(16),
    width: _Matrics.default.screenWidth - _Matrics.default.s(32),
    position: 'absolute',
    zIndex: 10,
    bottom: _Matrics.default.vs(20),
    // backgroundColor: colors.labelDarkGray,
    borderRadius: _Matrics.default.vs(12),
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'space-between'
  },
  toastTxt: {
    // color: colors.white,
    fontSize: _Matrics.default.mvs(12),
    lineHeight: _Matrics.default.vs(16)
    // fontFamily: fonts.BOLD,
  },
  optionHeader: {
    marginTop: _Matrics.default.vs(24),
    marginBottom: _Matrics.default.vs(12),
    marginHorizontal: _Matrics.default.s(16),
    fontWeight: 'bold',
    // color: colors.labelDarkGray,
    fontSize: _Matrics.default.mvs(18),
    lineHeight: _Matrics.default.mvs(24)
  },
  goalBtn: {
    marginHorizontal: _Matrics.default.s(16),
    paddingVertical: _Matrics.default.vs(10),
    paddingHorizontal: _Matrics.default.s(16),
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'space-between',
    // backgroundColor: colors.white,
    borderRadius: _Matrics.default.vs(12)
    // ...globalStyles.shadowContainer,
  },
  goalText: {
    fontWeight: '700',
    fontSize: _Matrics.default.mvs(14),
    lineHeight: _Matrics.default.mvs(18)
    // color: colors.labelDarkGray,
  },
  disclaimer: {
    // color: colors.inactiveGray,
    fontSize: _Matrics.default.vs(12),
    lineHeight: _Matrics.default.mvs(16),
    // fontFamily: Fonts.REGULAR,
    marginVertical: _Matrics.default.vs(4)
  },
  uploadReportTitleTxt: {
    // fontFamily: Fonts.REGULAR,
    fontSize: _Matrics.default.mvs(12),
    lineHeight: 16,
    // color: colors.labelDarkGray,
    flex: 1
  },
  uploadReportSubTitleTxt: {
    // fontFamily: Fonts.BOLD,
    fontSize: _Matrics.default.mvs(10),
    lineHeight: 13,
    // color: colors.white,
    flex: 1,
    marginTop: _Matrics.default.vs(2)
    // backgroundColor: 'red',
  },
  healthCheckupContainer: {
    marginVertical: _Matrics.default.vs(25),
    marginHorizontal: _Matrics.default.s(15),
    marginBottom: 0
    // borderColor: colors.onco.SURFACE_BACKGROUND_TERTIARY,
  },
  // Tabs styles
  tabContainer: {
    flexDirection: 'row',
    alignItems: 'center',
    marginTop: _Matrics.default.vs(6),
    // borderBottomColor: colors.lightGrey,
    borderBottomWidth: 1,
    marginBottom: _Matrics.default.vs(20)
  },
  tab: {
    flex: 1,
    alignItems: 'center',
    justifyContent: 'center',
    paddingVertical: _Matrics.default.vs(6),
    borderBottomWidth: 2
    // borderBottomColor: colors.transparent,
  },
  tabText: {
    color: '#888888',
    fontSize: _Matrics.default.mvs(14),
    fontWeight: '500',
    lineHeight: _Matrics.default.mvs(18)
  },
  active: {
    borderBottomWidth: 2
    // borderBottomColor: colors.careplix.button_background_primary,
  },
  activeText: {
    // color: colors.careplix.button_background_primary,
    fontSize: _Matrics.default.mvs(14),
    fontWeight: '700',
    lineHeight: _Matrics.default.mvs(18)
  },
  // Fibroid styles
  symptomsContainer: {
    paddingTop: _Matrics.default.vs(20),
    overflow: 'hidden'
  },
  bgCircles: {
    width: _Matrics.default.screenWidth,
    minHeight: _Matrics.default.screenWidth
  },
  detailContainer: {
    paddingHorizontal: _Matrics.default.s(16),
    gap: _Matrics.default.vs(16)
  },
  text1: {
    // ...globalStyles.ONCO_HEADER_1,
    // color: colors.onco.TEXT_PRIMARY,
  },
  text2: {
    // ...globalStyles.ONCO_BODY_REGULAR_1,
    // color: colors.onco.TEXT_PRIMARY,
  },
  fibroidProgressBannerScore: {
    height: _Matrics.default.vs(150),
    width: _Matrics.default.vs(150),
    top: _Matrics.default.vs(12),
    left: _Matrics.default.s(20),
    transform: 'scale(1.1)'
  },
  iconContainer: {
    minHeight: _Matrics.default.vs(200),
    flexDirection: 'row',
    justifyContent: 'space-between'
  },
  careNavigatorGirl: {
    height: _Matrics.default.screenWidth * 0.7,
    width: _Matrics.default.screenWidth * 0.6,
    right: _Matrics.default.vs(12),
    bottom: _Matrics.default.vs(-20)
  },
  flower: {
    width: _Matrics.default.vs(160),
    height: _Matrics.default.vs(160),
    marginVertical: _Matrics.default.vs(8),
    position: 'absolute',
    bottom: _Matrics.default.vs(-40),
    left: _Matrics.default.s(-40)
  },
  goodflipContainer: {
    flex: 1
  },
  tabsRow: {
    flexDirection: 'row',
    backgroundColor: _colors.colors.white,
    paddingTop: _Matrics.default.vs(10),
    alignItems: 'center'
  },
  tabButton: {
    flex: 1,
    alignItems: 'center',
    // backgroundColor: colors.white,
    paddingTop: _Matrics.default.vs(10)
  },
  tabButtonInner: {
    paddingHorizontal: _Matrics.default.s(10),
    paddingVertical: _Matrics.default.vs(6),
    borderRadius: _Matrics.default.mvs(100),
    gap: 8,
    flexDirection: 'row',
    alignItems: 'center'
  },
  tabButtonText: {
    fontSize: _Matrics.default.mvs(15)
    // color: colors.dark_jungle_green,
    // fontFamily: Fonts.ROBOTO_REGULAR,
  },
  activeTabButtonText: {
    // color: colors.brunswick_green,
    // fontFamily: Fonts.ROBOTO_BOLD,
  },
  tabBottomBar: {
    height: _Matrics.default.vs(5),
    width: '50%',
    borderTopRightRadius: _Matrics.default.mvs(100),
    borderTopLeftRadius: _Matrics.default.mvs(100),
    marginTop: _Matrics.default.vs(4)
    // backgroundColor: colors.white,
  },
  activeTabBottomBar: {
    // backgroundColor: colors.illuminating_emerald,
  },
  tabContent: {
    flex: 1
    // backgroundColor: colors.white,
  },
  errorContainer: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: _colors.colors.white
  },
  errorText: {
    fontSize: _Matrics.default.mvs(16),
    color: '#FF3B30',
    fontWeight: '500',
    textAlign: 'center',
    paddingHorizontal: _Matrics.default.s(20)
  }
});
//# sourceMappingURL=ProgressWebView.js.map