import axios from "axios";
import FingerprintJS from "fingerprintjs2";

interface ActivityData {
  userId?: any;
  source?: any;
  page?: any;
  action?: any;
  ipAddress?: string;
  userAgent?: any;
  from?: string; // Previous URL
  url?: string; // Current URL
  deviceId?: string;
}

const getDeviceId = async (): Promise<string> => {
  const components = await FingerprintJS.getPromise();
  const values = components.map((component) => component.value);
  const deviceId = FingerprintJS.x64hash128(values.join(""), 31);
  return deviceId;
};

export const userActivity = async (
  userId?: any,
  source?: any,
  page?: any,
  action?: any,
  userAgent?: any,
  url?: string
): Promise<boolean> => {
  try {
    // Determine the current URL
    const currentUrl = url || window.location.href;

    // Retrieve the previous URL from sessionStorage
    const previousUrl =
      sessionStorage.getItem("previous_url") || "No previous URL";

    // Debugging: Log the previous and current URLs
    console.log("Previous URL:", previousUrl);
    console.log("Current URL:", currentUrl);

    // Retrieve the IP address from sessionStorage or fetch if not available
    const ipAddress = sessionStorage.getItem("_jazz_ip_address");
    const deviceId = await getDeviceId();

    if (!ipAddress) {
      const response = await fetch("https://api.ipify.org?format=json");
      const data = await response.json();
      sessionStorage.setItem("_jazz_ip_address", data.ip);

      const activityData: ActivityData = {
        userId,
        source,
        page,
        action,
        ipAddress: data.ip,
        userAgent,
        from: currentUrl, // Correctly set the previous URL
        url, // Correctly set the current URL
        deviceId,
      };

      await axios.post(
        "https://api.jazzagain.com/public/index.php/api/userActivity",
        activityData
      );
    } else {
      const activityData: ActivityData = {
        userId,
        source,
        page,
        action,
        ipAddress,
        userAgent,
        from: currentUrl, // Correctly set the previous URL
        url, // Correctly set the current URL
        deviceId,
      };

      await axios.post(
        "https://api.jazzagain.com/public/index.php/api/userActivity",
        activityData
      );
    }

    // Update the stored URL as the new previous URL
    sessionStorage.setItem("previous_url", currentUrl);

    return true;
  } catch (error) {
    console.error("Error saving activity:", error);
    return false;
  }
};
