
import { WebView } from "react-native-webview";
import { useIsFocused } from "@react-navigation/native";
import Modal from "react-native-modal";


const [surveydata, setSurveyData] = useState({});
const [modalVisiblesurvey, setModalVisibleSurvey] = useState(false);
const [surveyloader, setSurveyLoader] = useState(false);
const [isWebViewReady, setWebViewReady] = useState(false);
const webViewRef = useRef(null);
const isFocused = useIsFocused();

const ShowSurveyPopup = async () => {
  try {
    setSurveyLoader(true);
    const raw = JSON.stringify({
      ProjectId: "0",
      UserId: user?.emp_code,
      // UserId: "80307",

    });
    let res = await fetch(
      "https://api1.parinaam.in/api/cpminternal/GetPopupWeburl",
      {
        method: "POST",
        body: raw,
        headers: {
          Accept: "application/json",
          "Content-Type": "application/json",
        },
      }
    );
    let responseJson = await res.json();
    if (responseJson) {
      setSurveyData(responseJson?.GetPopupWeburl || {});
      // console.log("responseJson?.GetPopupWeburl[0]?.Status",responseJson?.GetPopupWeburl[0])
      if (responseJson?.GetPopupWeburl[0]?.Status) {
        setModalVisibleSurvey(false);
      } else {
        setModalVisibleSurvey(true);
      }

    } else {
      setSurveyData({});
    }
  } catch (error) {
    alert("Survey Popup:" + error);
  } finally {
    setSurveyLoader(false);
  }
};

useEffect(() => {
  ShowSurveyPopup();
}, [isFocused]);

let webUrl = surveydata[0]?.WebUrl;


const injectedJS = `
(function() {
  const element = document.getElementById('cpminternalclose');
  console.log(element, "element")
  if (element) {
    window.ReactNativeWebView.postMessage(JSON.stringify({ id: element.id }));
  } else {
    // window.ReactNativeWebView.postMessage(JSON.stringify({ message: "Element not found" }));
  }
})();
true;
`;

const handleMessage = (event) => {
  try {
    const data = JSON.parse(event.nativeEvent.data);
    if (data.error) {
      alert(data.error);
    } else {
      console.log('Element data:', data);
      if (data?.id == 'cpminternalclose') {
        setTimeout(() => {
          setModalVisibleSurvey(false);
          ShowSurveyPopup();
        }, 2000);
      } else {
        alert("Id not found");
      }

    }
  } catch (error) {
    alert('Error parsing message:', error);
  }
};



{
  <Modal
    animationType="slide"
    transparent={true}
    visible={modalVisiblesurvey}
    // visible={true}
    onRequestClose={() => setModalVisibleSurvey(false)}
  >
    <View style={styles.modalContainer}>
      <View style={styles.modalContent}>
        <ActivityIndicatior visible={surveyloader} />
        <WebView
          style={styles.webView}
          source={{ uri: webUrl }}
          cacheEnabled={false}  // Disable cache
          incognito={true}
          onLoadStart={() => setSurveyLoader(true)}
          onLoadEnd={() => {
            setSurveyLoader(false);
            // setWebViewReady(true);
            console.log("ENd Loadingggg...---");
          }}
          ref={webViewRef}
          injectedJavaScript={injectedJS}
          onMessage={handleMessage}
        />
      </View>
    </View>
  </Modal>
}