import { useEffect, useState } from "react";
import { Navigate, Outlet, useSearchParams } from "react-router-dom";
import { match } from "ts-pattern";
import { useMaybeUser } from "../providers/UserStoreProvider";
import { LoadingSpinner } from "./LoadingSpinner";

export const AuthenticationGateway = () => {
  const user = useMaybeUser();
  const [isLoading, setIsLoading] = useState(true);

  const [searchParams] = useSearchParams();
  const redirectUrl = searchParams.get("redirect");

  if (redirectUrl) {
    localStorage.setItem("redirectUrl", redirectUrl);
  }

  useEffect(() => {
    const timer = setTimeout(() => {
      setIsLoading(false);
    }, 200);
    return () => clearTimeout(timer);
  }, [user]);

  let status: "loading" | "should-redirect" | "should-pass" = "loading";
  if (isLoading) {
    status = "loading";
  } else if (user) {
    status = "should-redirect";
  } else {
    status = "should-pass";
  }

  return match(status)
    .with("loading", () => <LoadingSpinner />)
    .with("should-redirect", () => <Navigate to="/" replace />)
    .with("should-pass", () => <Outlet />)
    .exhaustive();
};
