import React, { useRef, useEffect, useState, useCallback, useMemo } from 'react';
import { StyleSheet, SafeAreaView, NativeModules, NativeEventEmitter, Linking, BackHandler, Platform, ActivityIndicator, Dimensions, Button } from 'react-native';
import { EventRegister } from 'react-native-event-listeners';
import { WebView } from 'react-native-webview';
import constants from './constants';
import axios from 'axios';
import { getEncryptedText, getDecryptedData } from './Services';
import MainWebView from './MainWebView';
import ProgressWebView from './ProgressWebView';
import { SheetManager, SheetProvider } from 'react-native-actions-sheet';
import '../src/Sheets';
import { Provider } from 'react-redux';
import { configureStore } from '@reduxjs/toolkit';
import createSagaMiddleware from '@redux-saga/core';
import rootReducer from './redux/slices';
import rootSaga from './redux/sagas';
const {
  MyReactNativeBridge
} = NativeModules;
const LINKING_ERROR = `The package 'react-native-mytatva-rn-sdk' doesn't seem to be linked. Make sure: \n\n` + Platform.select({
  ios: "- You have run 'pod install'\n",
  default: ''
}) + '- You rebuilt the app after installing the package\n' + '- You are not using Expo Go\n';
const escapeChars = {
  lt: '<',
  gt: '>',
  quot: '"',
  apos: "'",
  amp: '&'
};
const unescapeHTML = str =>
// modified from underscore.string and string.js
// eslint-disable-next-line no-useless-escape
str.replace(/\&([^;]+);/g, (entity, entityCode) => {
  let match;
  if (entityCode in escapeChars) {
    return escapeChars[entityCode];
  } else if (match = entityCode.match(/^#x([\da-fA-F]+)$/)) {
    return String.fromCharCode(parseInt(match[1], 16));
  } else if (match = entityCode.match(/^#(\d+)$/)) {
    return String.fromCharCode(match[1]);
  } else {
    return entity;
  }
});
const mytatvaEvent = 'mytatva-event';
const sagaMiddleware = createSagaMiddleware();
const store = configureStore({
  reducer: rootReducer,
  middleware: getDefaultMiddleware => getDefaultMiddleware().concat(sagaMiddleware)
});
sagaMiddleware.run(rootSaga);
const MyTatvaRnSdkView = ({
  mobileNumber,
  uuid,
  baseUrl,
  errorBaseUrl,
  token,
  environment,
  userMetaInfo,
  clientSource,
  moduleName,
  navigation
}) => {
  const [source, setSource] = useState('');
  const [loading, setLoading] = useState(false);
  const [isError, setError] = useState(false);

  // useEffect(() => {
  //   if ((baseUrl?.trim()?.length || 0) > 0) {
  //     setSource(baseUrl);
  //   }
  // }, [
  //   baseUrl,

  // ]);

  const MyTatvaRnSdkViewManager = useMemo(() => NativeModules.MyTatvaRnSdkViewManager ? NativeModules.MyTatvaRnSdkViewManager : new Proxy({}, {
    get() {
      throw new Error(LINKING_ERROR);
    }
  }), []);
  useEffect(() => {
    if (!uuid && !mobileNumber) {
      setTimeout(() => {
        EventRegister.emitEvent('mytatva-event', {
          message: 'unique-identifier',
          errorMessage: 'contact number or patientId is required'
        });
      }, 1000);
      setError(true);
    } else {
      authenticateSDK();
      setError(false);
    }
  }, [uuid, mobileNumber]);
  const webviewRef = useRef(null);
  const authenticateSDK = () => {
    setLoading(true);
    let baseUrl = environment.toUpperCase() === 'PROD' ? constants.PROD_BASE_URL : constants.STAGE_BASE_URL;
    const finalUrl = baseUrl + '/helper/authenticateClient';
    const data = {
      source: clientSource,
      sourceKey: token
    };
    axios({
      method: 'post',
      url: finalUrl,
      headers: {
        'api-key': environment.toUpperCase() === 'PROD' ? constants.PROD_API_KEY : constants.STAGE_API_KEY,
        'Content-Type': 'text/plain'
      },
      data: getEncryptedText(data, environment)
    }).then(async response => {
      const parsedResponse = await JSON.parse(getDecryptedData(response === null || response === void 0 ? void 0 : response.data, environment));
      if ((parsedResponse === null || parsedResponse === void 0 ? void 0 : parsedResponse.data) == 0) {
        setError(true);
        EventRegister.emitEvent('mytatva-event', {
          message: 'unauthorized-client',
          errorMessage: 'Unauthorized Access'
        });
      } else {
        getSourceUrl();
      }
    }).catch(error => {
      console.log("error", error);
    }).finally(() => {
      setLoading(false);
    });
  };
  useEffect(() => {
    const apiManagerEmitter = new NativeEventEmitter(MyTatvaRnSdkViewManager);
    const subscription = apiManagerEmitter.addListener('EventReminder', reminder => {});
    return () => {
      subscription.remove();
    };
  }, [MyTatvaRnSdkViewManager]);
  const getSourceUrl = () => {
    let finalUrl = '';
    const params = {
      uuid,
      mobileNumber,
      clientSource,
      moduleName,
      environment,
      ...userMetaInfo
    };
    let baseUrl = environment.toUpperCase() === 'PROD' ? constants.PROD_BASE_URL : constants.STAGE_BASE_URL;
    if (baseUrl) {
      finalUrl = baseUrl + '?data=' + encodeURIComponent(JSON.stringify(params));
      setSource(finalUrl);
    } else {
      console.log("No baseUrl");
    }
  };
  const handleMessage = async event => {
    var _webviewRef$current;
    const data = JSON.parse(unescapeHTML(event.nativeEvent.data));
    const {
      method,
      url
    } = data;
    switch (method) {
      case 'UPDATE_PLATFORM':
        (_webviewRef$current = webviewRef.current) === null || _webviewRef$current === void 0 || _webviewRef$current.injectJavaScript('window.setSdkPlatform("IOS")');
        break;
      case 'OPEN_PDF':
        Linking.openURL(url);
        break;
      case 'CLOSE_VIEW':
        break;
      default:
        break;
    }
  };
  const [canGoBack, setCanGoBack] = useState(false);
  const handleBack = useCallback(() => {
    if (canGoBack && webviewRef.current) {
      var _webviewRef$current2;
      (_webviewRef$current2 = webviewRef.current) === null || _webviewRef$current2 === void 0 || _webviewRef$current2.goBack();
      return true;
    }
    return false;
  }, [canGoBack]);
  useEffect(() => {
    BackHandler.addEventListener('hardwareBackPress', handleBack);
    return () => {
      BackHandler.removeEventListener('hardwareBackPress', handleBack);
      // gpsListener.remove();
    };
  }, [handleBack]);
  const openNativeScreen = () => {
    MyReactNativeBridge.openNativeFlow();
  };
  const {
    height,
    width
  } = Dimensions.get('screen');
  return (
    /*#__PURE__*/
    // eslint-disable-next-line react-native/no-inline-styles
    React.createElement(SafeAreaView, {
      style: {
        flex: 1,
        backgroundColor: 'white'
      }
    }, /*#__PURE__*/React.createElement(Provider, {
      store: store
    }, /*#__PURE__*/React.createElement(SheetProvider, null, /*#__PURE__*/React.createElement(Button, {
      title: "Open CGM",
      color: "#f194ff",
      onPress: openNativeScreen
    }), moduleName === 'progress' ? /*#__PURE__*/React.createElement(ProgressWebView, {
      token: token,
      environment: environment,
      source: source,
      loading: loading,
      isError: isError,
      webviewRef: webviewRef
      // runBeforeFirst={runBeforeFirst}
      ,
      setCanGoBack: setCanGoBack,
      mobileNumber: mobileNumber,
      moduleName: moduleName,
      platform: 'IOS',
      uuid: uuid,
      clientSource: clientSource
    }) : /*#__PURE__*/React.createElement(MainWebView, {
      token: token,
      environment: environment,
      source: source,
      loading: loading,
      platform: 'IOS',
      isError: isError,
      webviewRef: webviewRef,
      handleMessage: handleMessage
      // runBeforeFirst={runBeforeFirst}
      ,
      setCanGoBack: setCanGoBack,
      clientSource: clientSource,
      moduleName: moduleName
    }))))
  );
};
const styles = StyleSheet.create({
  webViewContainer: {
    flex: 1,
    backgroundColor: 'white'
  },
  webView: {
    flex: 1
  }
});
MyTatvaRnSdkView.defaultProps = {
  mobileNumber: '',
  uuid: '',
  token: '',
  baseUrl: '',
  errorBaseUrl: '',
  environment: '',
  metaInfo: {},
  clientSource: '',
  moduleName: ''
};
export default MyTatvaRnSdkView;
const LoadingIndicator = () => {
  return /*#__PURE__*/React.createElement(ActivityIndicator, {
    color: "#000",
    size: "small"
    // eslint-disable-next-line react-native/no-inline-styles
    ,
    style: {
      flex: 1,
      zIndex: 100,
      position: 'absolute',
      backgroundColor: '#fff',
      opacity: 0.4,
      width: '100%',
      height: '100%',
      justifyContent: 'center',
      alignItems: 'center'
    }
  });
};
//# sourceMappingURL=MyTatvaRnSdkView.ios.js.map