import { useContext, useEffect } from "react";
import { useQuery } from "urql";
import { toast } from "react-toastify";
import { AppStateContext } from "../../contexts/AppContext";
import { UserContext } from "../../contexts/UserContext";
import { Context as AuthContext } from "../../contexts/AuthContext";
import { User } from "../../types";
import { MeQueryDocument } from "../../gql-codegen/graphql";
import { SideBar } from "./_organisms/SideBar";
import Tabbar from "./_organisms/Tabbar";
import { useNavigate } from "react-router-dom";

export function Protected(props: React.PropsWithChildren<any>) {
  const auth = useContext(AuthContext);
  const appState = useContext(AppStateContext);
  const userContext = useContext(UserContext);
  const navigate = useNavigate();

  const [result] = useQuery({
    query: MeQueryDocument,
  });

  useEffect(() => {
    if (result.fetching) {
      return;
    }

    const user = result?.data?.me?.user as User;
    const success = result?.data?.me?.success as boolean;

    userContext.updateUser(user);

    if (!success) {
      navigate("/login");
    } else {
      if (user) {
        const [company] = user?.companies || [];

        if (!company || company == undefined) {
          toast.info(
            "We need a couple more details before you can continue...",
            {
              position: toast.POSITION.BOTTOM_RIGHT,
            },
          );

          navigate("/complete-onboarding");

          appState.updateOpenSidebar(false);
        } else {
          navigate(window.location.pathname);
          appState.updateOpenSidebar(true);
        }
      }
    }
  }, [result.fetching]);

  return auth.accessToken && result?.data?.me?.user ? (
    <div className="flex justify-end bg-dashboard-bg min-h-screen">
      <div
        className={`fixed top-0 left-0 bottom-0 w-64 transition duration-300 bg-sidebar-bg ${
          appState.getOpenSidebar() ? "translate-x-0" : " -translate-x-full"
        } `}
      >
        <SideBar user={result?.data?.me?.user as User} />
      </div>

      <div
        className={`flex flex-col transition-width duration-300 ${
          appState.getOpenSidebar() ? "w-[calc(100%-16rem)]" : "w-full"
        } `}
      >
        <Tabbar openSideBar={appState.getOpenSidebar()} />
        <div className="flex p-10 bg-dashboard-bg">{props.children}</div>
      </div>
    </div>
  ) : (
    <></>
  );
}
