import { useSearchParams } from "react-router-dom";
import type { DiscordOnboardingState } from "../../../doorman-api/src/functions/api/door/onboard";
import { Spinner } from "@cloudscape-design/components";
import { useEffect } from "react";

export const RedirectPage = () => {
  const [params, setParams] = useSearchParams();

  const state: DiscordOnboardingState = JSON.parse(params.get("state") as string);
  const discordToken: string = params.get("code") as string;

  // if this is not a redirect, then go home
  if (!state || !discordToken) {
    window.location.href = '/';
  }

  useEffect(() => {
    fetch(state.apiRedirect + '?' + params.toString())
      .then(res => res.json())
      .then(res => {
        if (res.msg) {
          console.error(res);
          window.location.href = '/';
          return;
        }
        
        window.location.href = res.redirect;
      });
  }, []);

  return <Spinner />;
}