import type { ReactElement } from 'react';
import { useEffect } from 'react';
import { useRouter } from 'next/router';

import LayoutGuest from '../layouts/Guest';

export default function BuyerLoginRedirect() {
  const router = useRouter();

  useEffect(() => {
    if (!router.isReady) {
      return;
    }

    const returnTo = Array.isArray(router.query.returnTo)
      ? router.query.returnTo[0]
      : router.query.returnTo || '/buyer-portal/';

    router.replace({
      pathname: '/login',
      query: {
        returnTo,
      },
    });
  }, [router]);

  return null;
}

BuyerLoginRedirect.getLayout = function getLayout(page: ReactElement) {
  return <LayoutGuest>{page}</LayoutGuest>;
};
