import { Link, Outlet, useLoaderData, useRouteError } from "@remix-run/react";
import { boundary } from "@shopify/shopify-app-remix/server";
import { AppProvider } from "@shopify/shopify-app-remix/react";
import { NavMenu } from "@shopify/app-bridge-react";
import polarisStyles from "@shopify/polaris/build/esm/styles.css?url";
import { authenticate } from "../shopify.server";
import prisma from "../db.server";

export const links = () => [{ rel: "stylesheet", href: polarisStyles }];
function sleep(ms) {
  return new Promise((resolve) => setTimeout(resolve, ms));
}
export const loader = async ({ request }) => {
  await authenticate.admin(request);
   const { session } = await authenticate.admin(request);

  let user = await prisma.users.findFirst({
    where: { shopurl: session.shop }
  });
  
  if (!user) {
    await sleep(2000);
      user = await prisma.users.findFirst({
      where: {
        shopurl: session.shop,
      },
    });
    
  }
  return { apiKey: process.env.SHOPIFY_API_KEY || "" , user: user  };
};

export default function App() {
  const { apiKey, user } = useLoaderData();
  let route ;

  if (user?.setup_step == 'Done') {
    route = (
      <>
      {/* <Link to="/app/">Home</Link> */}
      <Link to="/app" rel="home">
          Home
        </Link>
        <Link to="/app/products">Products</Link>
        <Link to="/app/account">Amazon Account</Link>
        <Link to="/app/settings">Settings</Link>
        <Link to="/app/plan">Plan And Pricing</Link>
        <Link to="/app/faq">FAQ</Link>
      </>
    );
  }

  return (
    <AppProvider isEmbeddedApp apiKey={apiKey}>
      <NavMenu>
        {route}
      </NavMenu>
      <Outlet />
    </AppProvider>
  );
}

// Shopify needs Remix to catch some thrown responses, so that their headers are included in the response.
export function ErrorBoundary() {
  return boundary.error(useRouteError());
}

