import { useContext, useState, useEffect } from "reactn";
import * as Linking from "expo-linking";

import { UserDataContext } from "./UserDataProvider";
import { isWeb } from "../hooks/useLayoutType";
import { navigateToTask } from "../navigation/NavigationService";
import { SplashAnimationContext } from "./SplashAnimationProvider";

const appJson = require("../../app.json");

export const storeURL = {
  apple: "apps.apple.com/app/id1661696886",
  google: "play.google.com/store/apps",
};

const UniversalLinkProvider = ({ children }) => {
  const { currentUID } = useContext(UserDataContext);
  const { isFullyLoaded } = useContext(SplashAnimationContext);

  const [tempTaskData, setTempTaskData] = useState(null);

  useEffect(() => {
    const handleDeepLink = async (event) => {
      console.log("event", event);

      const { path = "", queryParams } = Linking.parse(event.url);

      console.log("path", path);
      console.log("queryParams", queryParams);

      const appSchemeURL = `${
        appJson.expo.scheme
      }://app/${path}?${new URLSearchParams(queryParams).toString()}`;

      const appStoreURL = `itms-apps://${storeURL.apple}`;

      if (isWeb) {
        const userAgent =
          navigator.userAgent || navigator.vendor || window.opera;
        const isIOSBrowser =
          /iPad|iPhone|iPod/.test(userAgent) ||
          (/Macintosh/.test(userAgent) &&
            navigator.maxTouchPoints &&
            navigator.maxTouchPoints > 2);

        if (isIOSBrowser) {
          try {
            const canOpen = await Linking.canOpenURL(appSchemeURL);
            if (canOpen) {
              window.location.href = appSchemeURL;
            } else {
              window.location.href = appStoreURL;
            }
          } catch (error) {
            console.error("Redirection error:", error);
            handleParams(path);
          }
        } else {
          handleParams(path);
        }
      } else {
        handleParams(path);
      }
    };

    const initDeepLinkHandling = async () => {
      const initialUrl = await Linking.getInitialURL();
      if (initialUrl) {
        console.log("Initial URL:", initialUrl);
        handleDeepLink({ url: initialUrl });
      }

      Linking.addEventListener("url", handleDeepLink);

      return () => {
        Linking.removeEventListener("url", handleDeepLink);
      };
    };

    initDeepLinkHandling();
  }, []);

  useEffect(() => {
    if (tempTaskData && currentUID && isFullyLoaded) {
      console.log("try to navigate to task");
      navigateToTask(tempTaskData);
      setTempTaskData(null);
    }
  }, [tempTaskData, currentUID, isFullyLoaded]);

  const handleParams = (path) => {
    console.log("path", path);

    cleanURL();
  };

  const cleanURL = () => {
    if (isWeb) {
      const url = new URL(window.location);

      console.log(url);

      url.search = "";
      window.history.replaceState({}, document.title, url.origin.toString());
    }
  };

  return children;
};

export default UniversalLinkProvider;
