import { BackHandler, Dimensions, View } from 'react-native';
import React, { useEffect, useRef } from 'react';
import MyWebView from 'react-native-autoheight-webview';

const MyWebView = () => {
  const webViewRef = useRef(null);
  /**
   * @function handleMessage
   * @param {String} message
   * @description this is the message from React PWA. Handle it here
   */
  const handleMessage = (message = null) => {
    // alert(JSON.stringify(message?.nativeEvent?.data));
  };

  /**
   * @function sendMsgToPWA
   * @description send any msg from React native app to PWA web
   * @description this method will also be fired when the web view loaded succesfully - did mount 1st time - onLoad prop in <Webview>
   */
  const sendMsgToPWA = () => {
    if (webViewRef?.current) {
      webViewRef?.current?.postMessage("Hi to React - from React native");
    }
  };

  return (
    <View style={[AppStyles.Flex1, AppStyles.AlignItemsCenter, AppStyles.JustifyContentCenter]}>
      <MyWebView
        ref={webViewRef} // Assign webview ref to the `webViewRef` while initial rendering
        source={{ uri }}
        style={{ width: Dimensions.get('window').width }}
        renderLoading={() => <CustomLoader />}
        mediaCapturePermissionGrantType="grant"
        userAgent="Mozilla/5.0 (Macintosh; Intel Mac OS X 13_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/114.0.0.0 Safari/537.36"
        startInLoadingState
        javaScriptEnabled
        domStorageEnabled
        cacheEnabled
        thirdPartyCookiesEnabled
        allowsProtectedMedia
        allowUniversalAccessFromFileURLs
        allowsInlineMediaPlayback
        mediaPlaybackRequiresUserAction={false}
        onMessage={handleMessage}
        onLoadEnd={sendMsgToPWA}
      />
    </View>
  );
};

export default MyWebView;