import {
  extractAPIKeyFromURL,
  extractPageIdFromURL,
} from "@app/services/utilities";
import { useSettings } from "@settings/contexts/SettingsContext";
import React, { useEffect } from "react";
import { useNavigate } from "react-router-dom";

const Redirect = () => {
  const navigate = useNavigate();
  const { initialSettings, emptyConfigList } = useSettings();

  const handleNewToken = async () => {
    const page_id = extractPageIdFromURL(window.location.href);
    const apiKeyFromParam = extractAPIKeyFromURL(window.location.href);

    if (!initialSettings?.api_key || !!apiKeyFromParam || emptyConfigList) {
      navigate("/configuration", { replace: true });
      return;
    }

    if (!page_id) {
      navigate("/grid-manager", { replace: true });
      return;
    }

    navigate(`/configuration/${page_id}`, {
      replace: true,
    });
  };

  useEffect(() => {
    handleNewToken();
  }, []);

  return <></>;
};

export default Redirect;
