import React, { useEffect, useState } from "react";
import { encryptData } from "./functions/encryptData";
import axios from "axios";
import { clickEvent } from "./events/click";
import { scrollEvent } from "./events/scroll";
import { checkIPAddress } from "./functions/checkIPAddress";
import { locationChange } from "./events/locationChange";

const allowedEvents = {
  clickEnabled: true,
  scrollEnabled: true,
  locationEnabled: true,
};

const EventAnalytics = ({
  events,
  locationProp,
}: {
  events?: any;
  locationProp: any;
}) => {
  const [IPV4, setIPV4] = useState("");
  const [IPV6, setIPV6] = useState("");
  let location: any;
  if (typeof window !== "undefined") {
    location = window.location;
  }

  useEffect(() => {
    console.log("event listeners check", events);
    if (events.clickEnabled) {
      clickEvent({ IPV4, IPV6 });
    }
    if (events.scrollEnabled) {
      scrollEvent({ IPV4, IPV6 });
    }
    if (events.locationEnabled) {
      locationChange({ IPV4, IPV6 });
    }
    if (typeof window !== "undefined") {
      window.addEventListener("popstate", function (event) {
        scrollEvent({ IPV4, IPV6 });
      });
    }
  }, []);

  useEffect(() => {
    console.log("event listeners check", events, location);

    if (events.scrollEnabled) {
      scrollEvent({ IPV4, IPV6 });
    }
  }, [locationProp]);

  useEffect(() => {
    // GET IPV4 AND IPV6
    axios.get("https://api.ipify.org?format=json").then((response: any) => {
      if (checkIPAddress(response.data.ip) == "IPv4") {
        setIPV4(response.data.ip);
      }
    });
    axios.get("https://api64.ipify.org?format=json").then((response: any) => {
      if (checkIPAddress(response.data.ip) == "IPv6") {
        setIPV6(response.data.ip);
      }
    });
  }, []);

  return null;
};

export default EventAnalytics;

EventAnalytics.defaultProps = {
  events: allowedEvents,
  locationProp: typeof window != "undefined" && window.location,
};
