import React, { useEffect } from 'react';
import NextRouterLink from 'next/link';
import { useRouter } from 'next/router';
import { Link, LinkProps } from '@digigov/ui/navigation/Link';

const NextLink: React.ForwardRefRenderFunction<HTMLAnchorElement, LinkProps> = (
  props,
  ref
) => {
  const { href, as, ...other } = props;
  const isExternalLink =
    /^(?:[a-z]+:)?\/\/|\.pdf|\.docx?|\.xlsx?|^mailto:/i.test(href || '') ||
    other.target === '_blank';

  const router = useRouter();

  useEffect(() => {
    const path = router.asPath;
    if (path.includes('#')) {
      setTimeout(() => {
        const id = path.replace('#', '');
        const el = document.getElementById(id);
        if (el) {
          window.scroll({
            top: scrollY + el.getBoundingClientRect().top,
            behavior: 'smooth',
          });
        }
      }, 600);
    }
  }, [router.asPath]);

  if (isExternalLink) {
    return (
      <Link ref={ref} href={href || '#'} {...other}>
        {props.children}
      </Link>
    );
  }

  return (
    <NextRouterLink href={href || '#'} as={undefined} {...other}>
      <Link ref={ref} {...other} as={as}>
        {props.children}
      </Link>
    </NextRouterLink>
  );
};

export default React.forwardRef(NextLink);
