import React, { useRef, useEffect, useState, useCallback } from 'react';
import { EventRegister } from 'react-native-event-listeners';
import { NavigationContainer } from '@react-navigation/native';
// import { createStackNavigator } from '@react-navigation/stack';

import { SafeAreaView, BackHandler, Linking, AppState, ActivityIndicator, View, Text, NativeModules, Button, Alert } from 'react-native';
import './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';

// import {enableScreens} from 'react-native-screens';

import axios from 'axios';
import constants from './constants';
import { getEncryptedText, getDecryptedData } from './Services';
import MainWebView from './MainWebView';
import ProgressWebView from './ProgressWebView';
import { SheetManager, SheetProvider } from 'react-native-actions-sheet';

// enableScreens();

// const Stack = createStackNavigator();

export const httpClient = axios.create({
  timeout: 60000,
  headers: {
    'api-key': 'lChjFRJce3bxmoS3TSQk5w==',
    'Content-Type': 'text/plain'
  }
});
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 [appState, setAppState] = useState(AppState.currentState);
  const [loading, setLoading] = useState(false);
  const [isError, setError] = useState(false);

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

  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]);
  useEffect(() => {
    const subscription = AppState.addEventListener('change', handleAppStateChange);
    console.log(`AppState.addEventListener added, current state: ${appState}`);
    return () => {
      subscription.remove();
    };
  }, [appState]); // Include appState in the dependency array to ensure it's up to date.

  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);
    });
  };
  const handleAppStateChange = nextAppState => {
    // console.log(
    //   "nextAppState: " + nextAppState + ", previousState: " + appState
    // );

    // Instead of relying on the old appState, use the nextAppState directly
    if (appState.match(/inactive|background/) && nextAppState === 'active') {
      if (isLoggingEnabled) {
        console.log('App has come to the foreground!');
      }
      // getHealthConnectStatus();
    }

    // setAppState(nextAppState); // Update the state with the new app state
  };
  const webviewRef = useRef(null);
  const runBeforeFirst = `
        window.isNativeApp = true;
        window.platform = "ANDROID";
        window.setSdkPlatform('ANDROID');
        true; // note: this is required, or you'll sometimes get silent failures
    `;

  // console.log("runBeforeFirst====", runBeforeFirst)
  const handleMessage = event => {
    var _webviewRef$current;
    console.log("event====", event);
    if (event.nativeEvent.data != null) {
      try {
        const parsedObject = JSON.parse(event.nativeEvent.data);
        if (parsedObject.method != null) {
          switch (parsedObject.method) {
            case 'UPDATE_PLATFORM':
              (_webviewRef$current = webviewRef.current) === null || _webviewRef$current === void 0 || _webviewRef$current.injectJavaScript('window.setSdkPlatform("ANDROID")');
              break;
            case 'OPEN_PDF':
              {
                let pdfUrl = parsedObject.url;
                // console.log("pdfUrl "+pdfUrl);

                Linking.openURL(pdfUrl);
              }
              break;
            case 'CLOSE_VIEW':
              break;
            case 'OPEN_URL_HANDLER':
              navigation.navigate('UrlHandler', {
                url: parsedObject.url
              });
              break;
            case 'START_CGM_TRACKY':
              break;
            default:
              break;
          }
        }
      } catch (exception) {
        console.log('Exception occurred:' + exception.message);
      }
    }
  };
  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 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 startCgm = async () => {
    try {
      const result = await CgmTrackyLib.startCgmTracky();
      console.log(result);
    } catch (error) {
      console.error(error);
    }
  };
  const observeCgmData = async () => {
    try {
      CgmTrackyLib.observeAllGlucoseData();
      CgmTrackyLib.observeDeviceStatus();
    } catch (error) {
      console.error(error);
    }
  };
  const observeDeviceStaus = async () => {
    try {
      const result = await CgmTrackyLib.observeDeviceStatus();
      console.log(result);
    } catch (error) {
      console.error(error);
    }
  };
  return /*#__PURE__*/React.createElement(SafeAreaView, {
    style: {
      flex: 1,
      backgroundColor: 'white'
    }
  }, /*#__PURE__*/React.createElement(Provider, {
    store: store
  }, /*#__PURE__*/React.createElement(SheetProvider, null, /*#__PURE__*/React.createElement(Button, {
    title: "Press me",
    color: "#f194ff",
    onPress: startCgm
  }), /*#__PURE__*/React.createElement(Button, {
    title: "Observe CGM Data",
    color: "#008000",
    onPress: observeCgmData
  }), /*#__PURE__*/React.createElement(Button, {
    title: "Observe Device Status",
    color: "#427ef5",
    onPress: observeDeviceStaus
  }), moduleName === 'progress' ? /*#__PURE__*/React.createElement(ProgressWebView, {
    token: token,
    environment: environment,
    source: source,
    loading: loading,
    isError: isError,
    webviewRef: webviewRef,
    runBeforeFirst: runBeforeFirst,
    setCanGoBack: setCanGoBack,
    mobileNumber: mobileNumber,
    platform: 'ANDROID',
    moduleName: moduleName,
    uuid: uuid,
    clientSource: clientSource
  }) : /*#__PURE__*/React.createElement(MainWebView, {
    token: token,
    environment: environment,
    source: source,
    loading: loading,
    platform: 'ANDROID',
    isError: isError,
    webviewRef: webviewRef,
    handleMessage: handleMessage,
    runBeforeFirst: runBeforeFirst,
    setCanGoBack: setCanGoBack,
    clientSource: clientSource,
    moduleName: moduleName
  }))));
};
export default MyTatvaRnSdkView;
MyTatvaRnSdkView.defaultProps = {
  mobileNumber: '',
  uuid: '',
  token: '',
  baseUrl: '',
  errorBaseUrl: '',
  environment: '',
  metaInfo: {},
  clientSource: '',
  moduleName: '',
  navigation: {}
};
//# sourceMappingURL=MyTatvaRnSdkView.android.js.map