import { Link, Outlet, isRouteErrorResponse, useParams, useRouteError } from "@remix-run/react";
import posthog from "posthog-js";
import { useEffect } from "react";
import { useAppLayoutData } from "~/hooks/useAppLayoutData";
import { Routes } from "~/routes";

export function ErrorBoundary() {
  const params = useParams();
  const error = useRouteError();

  if (isRouteErrorResponse(error)) {
    return (
      <div className={"p-8"}>
        <h1>
          {error.status} {error.statusText}
        </h1>
        <p>{error.data}</p>
      </div>
    );
  } else if (error instanceof Error) {
    return (
      <div className={"p-8"}>
        <h1 className={"text-4xl font-medium"}>An error occurred, sorry about that!</h1>
        <Link
          to={Routes.app.project.env.dashboard({
            projectId: params.projectId!,
            envId: params.envId!,
          })}
          className={"text-2xl underline underline-offset-2"}
        >
          <h2>Go back home</h2>
        </Link>
        {process.env.NODE_ENV === "development" ? (
          <div>
            <p>{error.message}</p>
            <p>The stack trace is:</p>
            <pre>{error.stack}</pre>
          </div>
        ) : null}
      </div>
    );
  } else {
    return <h1>Unknown Error</h1>;
  }
}

export default function AppLayout() {
  const appLayoutData = useAppLayoutData();

  useEffect(() => {
    if (process.env.NODE_ENV !== "development" && appLayoutData?.user) {
      const name = appLayoutData.user.firstName + " " + appLayoutData.user.lastName;
      const email = appLayoutData.user.emailAddresses[0].emailAddress;
      posthog.identify(appLayoutData.user.id, { email, name });
    }
  }, [appLayoutData?.user]);

  return (
    <div className="h-screen w-screen px-4 pb-1 pt-4">
      <Outlet />
    </div>
  );
}
