import React from 'react';
import { ActivityIndicator, SafeAreaView } from 'react-native';
import { EventRegister } from 'react-native-event-listeners';
import WebView from 'react-native-webview';

const MainWebView = (props) => {
  const {
    url,
    source,
    loading,
    isError,
    webviewRef,
    handleMessage,
    runBeforeFirst,
    platform,
    setCanGoBack,
  } = props; // Get the URL and other parameters from the route

  return (
    <SafeAreaView style={{ flex: 1 }}>
      {(isError || loading) && <LoadingIndicator />}
      {source && !isError && !loading ? (
        <WebView
          ref={webviewRef}
          source={{
            uri: source,
            headers: {
              platform: platform,
            },
          }}
          onMessage={handleMessage}
          {...(runBeforeFirst && {
            injectedJavaScriptBeforeContentLoaded: runBeforeFirst,
          })}
          javaScriptEnabled={true}
          onLoadProgress={(event) => setCanGoBack(event.nativeEvent.canGoBack)}
          onError={(errorMessage) => {
            EventRegister.emitEvent('mytatva-event', {
              message: 'web-view-error',
              errorMessage: errorMessage,
            });
          }}
        />
      ) : null}
    </SafeAreaView>
  );
};

export default MainWebView;

const LoadingIndicator = () => {
  return (
    <ActivityIndicator
      color="#000"
      size="large"
      // 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',
      }}
    />
  );
};
