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 React, { useEffect, useMemo, useState } from 'react';
import { View, Text, StyleSheet, TouchableOpacity, Platform, NativeModules } from 'react-native';
import { colors } from './helpers/colors';
import Matrics from './helpers/Matrics';
import { Icons } from './helpers/icons';
import WebView from 'react-native-webview';
// import { globalStyles } from '../../../../src/helpers/globalStyles';
import { SheetManager } from 'react-native-actions-sheet';
import { initializeTracky } from 'react-native-tracky-lib';
// import { API_URL, APP_MODE } from '@env';
import { useDispatch, useSelector } from 'react-redux';
import * as actions from './redux/slices';
import { EventRegister } from 'react-native-event-listeners';
import constants from './constants';
import { getDiseaseType, getTherapyArea } from './helpers/common';
const {
  CgmTrackyLib
} = 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] = useState('GoodflipProgressAchieveSectionScreen');
  const baseUrl = environment.toUpperCase() === 'PROD' ? constants.PROD_BASE_URL : constants.STAGE_BASE_URL;
  const goodflipUrl = environment.toUpperCase() === 'PROD' ? constants.PROD_GOODFLIP_URL : constants.STAG_GOODFLIP_URL;
  const appGoodflipUrl = environment.toUpperCase() === 'PROD' ? constants.PROD_APP_GOODFLIP_URL : constants.STAG_APP_GOODFLIP_URL;
  const dispatch = useDispatch();
  const {
    user
  } = useSelector(state => state.Auth);
  const [url, setUrl] = useState('');
  const [isLoading, setIsLoading] = useState(false);
  const [hasError, setHasError] = useState(false);
  const [isFreeUser, setIsFreeUser] = useState(false);
  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: getTherapyArea(user === null || user === void 0 ? void 0 : user.data) || 'metabolism',
      conditionName: 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
    }));
  };
  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);
    });
  };
  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 = useMemo(() => {
    const tabs = [{
      id: 'GoodflipProgressAchieveSectionScreen',
      title: 'Achieve',
      icon: focused => focused ? /*#__PURE__*/React.createElement(Icons.AchieveIcon, {
        fill: 'black'
      }) : null,
      url: 'GoodflipProgressAchieveSectionScreen'
    }, {
      id: 'GoodflipProgressVitalsSectionScreen',
      title: 'Vitals',
      icon: focused => focused ? /*#__PURE__*/React.createElement(Icons.HeartIcon, {
        fill: 'black'
      }) : null,
      url: 'GoodflipProgressVitalsSectionScreen'
    }, {
      id: 'GoodflipProgressDeviceSectionScreen',
      title: 'Devices',
      icon: focused => focused ? /*#__PURE__*/React.createElement(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') {
      SheetManager.show('bca_device_list_sheet', {
        payload: {
          onPressConnectSmartScaleBtn: deviceType => {
            SheetManager.hide('bca_device_list_sheet').then(() => {
              if ((deviceType === null || deviceType === void 0 ? void 0 : deviceType.device_type) === 'GoodFlip') {
                initializeTracky({
                  age: Number(age),
                  gender: gender,
                  height: Number(Number(height).toFixed(0))
                });
              }
            });
          }
        }
      });
    } else if (action === 'syncDevice') {
      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);
  return /*#__PURE__*/React.createElement(View, {
    style: styles.goodflipContainer
  }, !hasError && /*#__PURE__*/React.createElement(View, {
    style: styles.tabsRow
  }, goodflipTabs.map(tab => /*#__PURE__*/React.createElement(TouchableOpacity, {
    key: tab.id,
    style: styles.tabButton,
    onPress: () => setActiveGoodflipTab(tab.id)
  }, /*#__PURE__*/React.createElement(View, {
    style: [styles.tabButtonInner, {
      backgroundColor: activeGoodflipTab === tab.id ? 'honeydew' : 'white'
    }]
  }, /*#__PURE__*/React.createElement(Text, {
    style: [styles.tabButtonText, activeGoodflipTab === tab.id && styles.activeTabButtonText]
  }, tab.title)), /*#__PURE__*/React.createElement(View, {
    style: [styles.tabBottomBar, activeGoodflipTab === tab.id && styles.activeTabBottomBar]
  })))), hasError && /*#__PURE__*/React.createElement(View, {
    style: styles.errorContainer
  }, /*#__PURE__*/React.createElement(Text, {
    style: styles.errorText
  }, "Something went wrong")), url && !isError && !loading && !isLoading && !hasError ? /*#__PURE__*/React.createElement(WebView, _extends({
    ref: webviewRef,
    source: {
      uri: url,
      headers: {
        platform: platform
      }
    },
    onMessage: handleMessage
  }, runBeforeFirst && {
    injectedJavaScriptBeforeContentLoaded: runBeforeFirst
  }, {
    javaScriptEnabled: true,
    onError: errorMessage => {
      EventRegister.emitEvent('mytatva-event', {
        message: 'web-view-error',
        errorMessage: errorMessage
      });
    }
  })) : null);
};
export default ProgressWebView;
const styles = StyleSheet.create({
  container: {
    flex: 1
    // backgroundColor: colors.backgroundColor,
  },
  searchContainer: {
    marginHorizontal: Matrics.s(16),
    marginVertical: Matrics.vs(12),
    flexDirection: 'row',
    alignItems: 'center',
    ...(Platform.OS === 'ios' && {
      paddingVertical: Matrics.vs(12)
    }),
    paddingHorizontal: Matrics.s(12),
    gap: Matrics.s(8),
    // backgroundColor: colors.white,
    borderRadius: Matrics.vs(12),
    borderWidth: 1
    // borderColor: colors.lightGrey,
    // ...globalStyles.shadowContainer,
  },
  row: {
    flexDirection: 'row',
    alignItems: 'center',
    gap: Matrics.s(8)
  },
  toastContainer: {
    paddingVertical: Matrics.vs(12),
    paddingHorizontal: Matrics.s(16),
    marginHorizontal: Matrics.s(16),
    width: Matrics.screenWidth - Matrics.s(32),
    position: 'absolute',
    zIndex: 10,
    bottom: Matrics.vs(20),
    // backgroundColor: colors.labelDarkGray,
    borderRadius: Matrics.vs(12),
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'space-between'
  },
  toastTxt: {
    // color: colors.white,
    fontSize: Matrics.mvs(12),
    lineHeight: Matrics.vs(16)
    // fontFamily: fonts.BOLD,
  },
  optionHeader: {
    marginTop: Matrics.vs(24),
    marginBottom: Matrics.vs(12),
    marginHorizontal: Matrics.s(16),
    fontWeight: 'bold',
    // color: colors.labelDarkGray,
    fontSize: Matrics.mvs(18),
    lineHeight: Matrics.mvs(24)
  },
  goalBtn: {
    marginHorizontal: Matrics.s(16),
    paddingVertical: Matrics.vs(10),
    paddingHorizontal: Matrics.s(16),
    flexDirection: 'row',
    alignItems: 'center',
    justifyContent: 'space-between',
    // backgroundColor: colors.white,
    borderRadius: Matrics.vs(12)
    // ...globalStyles.shadowContainer,
  },
  goalText: {
    fontWeight: '700',
    fontSize: Matrics.mvs(14),
    lineHeight: Matrics.mvs(18)
    // color: colors.labelDarkGray,
  },
  disclaimer: {
    // color: colors.inactiveGray,
    fontSize: Matrics.vs(12),
    lineHeight: Matrics.mvs(16),
    // fontFamily: Fonts.REGULAR,
    marginVertical: Matrics.vs(4)
  },
  uploadReportTitleTxt: {
    // fontFamily: Fonts.REGULAR,
    fontSize: Matrics.mvs(12),
    lineHeight: 16,
    // color: colors.labelDarkGray,
    flex: 1
  },
  uploadReportSubTitleTxt: {
    // fontFamily: Fonts.BOLD,
    fontSize: Matrics.mvs(10),
    lineHeight: 13,
    // color: colors.white,
    flex: 1,
    marginTop: Matrics.vs(2)
    // backgroundColor: 'red',
  },
  healthCheckupContainer: {
    marginVertical: Matrics.vs(25),
    marginHorizontal: Matrics.s(15),
    marginBottom: 0
    // borderColor: colors.onco.SURFACE_BACKGROUND_TERTIARY,
  },
  // Tabs styles
  tabContainer: {
    flexDirection: 'row',
    alignItems: 'center',
    marginTop: Matrics.vs(6),
    // borderBottomColor: colors.lightGrey,
    borderBottomWidth: 1,
    marginBottom: Matrics.vs(20)
  },
  tab: {
    flex: 1,
    alignItems: 'center',
    justifyContent: 'center',
    paddingVertical: Matrics.vs(6),
    borderBottomWidth: 2
    // borderBottomColor: colors.transparent,
  },
  tabText: {
    color: '#888888',
    fontSize: Matrics.mvs(14),
    fontWeight: '500',
    lineHeight: Matrics.mvs(18)
  },
  active: {
    borderBottomWidth: 2
    // borderBottomColor: colors.careplix.button_background_primary,
  },
  activeText: {
    // color: colors.careplix.button_background_primary,
    fontSize: Matrics.mvs(14),
    fontWeight: '700',
    lineHeight: Matrics.mvs(18)
  },
  // Fibroid styles
  symptomsContainer: {
    paddingTop: Matrics.vs(20),
    overflow: 'hidden'
  },
  bgCircles: {
    width: Matrics.screenWidth,
    minHeight: Matrics.screenWidth
  },
  detailContainer: {
    paddingHorizontal: Matrics.s(16),
    gap: Matrics.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.vs(150),
    width: Matrics.vs(150),
    top: Matrics.vs(12),
    left: Matrics.s(20),
    transform: 'scale(1.1)'
  },
  iconContainer: {
    minHeight: Matrics.vs(200),
    flexDirection: 'row',
    justifyContent: 'space-between'
  },
  careNavigatorGirl: {
    height: Matrics.screenWidth * 0.7,
    width: Matrics.screenWidth * 0.6,
    right: Matrics.vs(12),
    bottom: Matrics.vs(-20)
  },
  flower: {
    width: Matrics.vs(160),
    height: Matrics.vs(160),
    marginVertical: Matrics.vs(8),
    position: 'absolute',
    bottom: Matrics.vs(-40),
    left: Matrics.s(-40)
  },
  goodflipContainer: {
    flex: 1
  },
  tabsRow: {
    flexDirection: 'row',
    backgroundColor: colors.white,
    paddingTop: Matrics.vs(10),
    alignItems: 'center'
  },
  tabButton: {
    flex: 1,
    alignItems: 'center',
    // backgroundColor: colors.white,
    paddingTop: Matrics.vs(10)
  },
  tabButtonInner: {
    paddingHorizontal: Matrics.s(10),
    paddingVertical: Matrics.vs(6),
    borderRadius: Matrics.mvs(100),
    gap: 8,
    flexDirection: 'row',
    alignItems: 'center'
  },
  tabButtonText: {
    fontSize: Matrics.mvs(15)
    // color: colors.dark_jungle_green,
    // fontFamily: Fonts.ROBOTO_REGULAR,
  },
  activeTabButtonText: {
    // color: colors.brunswick_green,
    // fontFamily: Fonts.ROBOTO_BOLD,
  },
  tabBottomBar: {
    height: Matrics.vs(5),
    width: '50%',
    borderTopRightRadius: Matrics.mvs(100),
    borderTopLeftRadius: Matrics.mvs(100),
    marginTop: Matrics.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.white
  },
  errorText: {
    fontSize: Matrics.mvs(16),
    color: '#FF3B30',
    fontWeight: '500',
    textAlign: 'center',
    paddingHorizontal: Matrics.s(20)
  }
});
//# sourceMappingURL=ProgressWebView.js.map