import { AppProps } from 'next/app';
import dynamic from 'next/dynamic';
import { ComponentType, Suspense } from 'react';
import { RelayProvider } from '@/core/relay';
import {
  IntlProvider,
  ErrorBoundary,
  AccountSettingsProvider,
  InitGoogleTagManager,
  InitActivityFlow,
  loadAccountSettingsQuery,
  InitSmartLook,
} from '@/core/components';
import 'fast-checkout/ui/styles/global.css';
import { usePathname } from 'next/navigation';

/*
 *  NOTE: O carregamento dos skeletons deve ser feito individual,
 *  pra garantir que não vamos carregar as queries de outras telas.
 */
import { InformationSkeleton } from '@/screens/Information/Information.skeleton';
import { CartSkeleton } from '@/screens/Cart/Cart.skeleton';
import { PaymentSkeleton } from '@/screens/Payment/Payment.skeleton';
import { ShippingSkeleton } from '@/screens/Shipping/Shipping.skeleton';
import { ReviewSkeleton } from '@/screens/Review/Review.skeleton';
import { MotionConfig } from 'framer-motion';
import { ExtensionPointsProvider } from '@/core/hooks';

const accountSettingsQueryRef = loadAccountSettingsQuery();

function App({ Component, pageProps }: AppProps) {
  // TODO: Remove after traffic split
  document.cookie = 'VtexCheckoutVersion=v2;max-age=43200';

  return (
    <ErrorBoundary>
      <RelayProvider>
        <IntlProvider locale="en-US">
          <Suspense fallback={<Skeleton />}>
            <ExtensionPointsProvider>
              <AccountSettingsProvider queryRef={accountSettingsQueryRef}>
                <MotionConfig reducedMotion="user">
                  <InitGoogleTagManager />
                  <InitSmartLook />
                  <InitActivityFlow />
                  <Component {...pageProps} />
                </MotionConfig>
              </AccountSettingsProvider>
            </ExtensionPointsProvider>
          </Suspense>
        </IntlProvider>
      </RelayProvider>
    </ErrorBoundary>
  );
}

function Skeleton() {
  const pathname = usePathname();

  switch (pathname) {
    case '/':
    case '/cart':
      return <CartSkeleton />;
    case '/information':
      return <InformationSkeleton />;
    case '/payment':
      return <PaymentSkeleton />;
    case '/shipping':
      return <ShippingSkeleton />;
    case '/review':
      return <ReviewSkeleton />;
    default:
      return <p>Loading...</p>;
  }
}

const NoSSR = <P,>(Component: ComponentType<P>) =>
  dynamic(() => Promise.resolve(Component), { ssr: false });

export default NoSSR(App);
