import React, {useState} from 'react';
import {useTranslation} from 'react-i18next';
import {WebView, WebViewMessageEvent} from '@components/_core/WebView';
import ActivityIndicator from '@components/ActivityIndicator';
import {Navigation} from '@interfaces/navigation';
import {showSnackbar} from '@redux/dispatchers';
import {Screens} from '@shared/constants';
import {HUMAND_URL} from '@shared/keys';

/**
 * JS script to send a "postMessage" when the review layout is rendered in the DOM.
 * This scripts depends on the elementId of the link: "review-layout". If the element doesn't exists, there is
 * a counter which stop the interval and send the same "postMessage".
 */
export const POST_MESSAGE_TRIGGER_JS = `
(function () {
  var counter = 0;
  var intervalRef = setInterval(function () {
    const reviewLayout = document.getElementById("review-layout");
    if (!!reviewLayout || counter >= 10) {
      window.ReactNativeWebView.postMessage("READY");
      clearInterval(intervalRef);
    } else {
      counter++;
    }
  }, 500);
})();
`;

export function ExternalFormScreen({
  route: {params},
}: Navigation<Screens.PERFORMANCE_REVIEW_EXTERNAL_FORM>) {
  const {t} = useTranslation();
  const [loading, setLoading] = useState(true);
  const uri = `${HUMAND_URL}performance/${params.cycleId}/external?id=${params.id}`;

  const onError = () =>
    showSnackbar({title: t('errors.api.404'), variant: 'error'});

  const onMessage = (event: WebViewMessageEvent) => {
    if (event.nativeEvent.data === 'READY') {
      setLoading(false);
    }
  };

  return (
    <>
      <WebView
        source={{uri}}
        bounces={false}
        onError={onError}
        onMessage={onMessage}
        injectedJavaScript={POST_MESSAGE_TRIGGER_JS}
      />
      {loading && <ActivityIndicator fullScreen />}
    </>
  );
}
