'use client';

import { useLocalization } from '@akinon/next/hooks';
import { LocaleUrlStrategy } from '@akinon/next/localization';
import { urlLocaleMatcherRegex, urlSchemes } from '@akinon/next/utils';
import NextLink, { LinkProps as NextLinkProps } from 'next/link';
import { useMemo } from 'react';

type LinkProps = Omit<
  React.AnchorHTMLAttributes<HTMLAnchorElement>,
  keyof NextLinkProps
> &
  NextLinkProps;

export const Link = ({ children, href, ...rest }: LinkProps) => {
  const { locale, defaultLocaleValue, localeUrlStrategy } = useLocalization();
  const formattedHref = useMemo(() => {
    if (!href) {
      return '#';
    }

    if (
      typeof href !== 'string' ||
      urlSchemes.some((scheme) => href.startsWith(scheme))
    ) {
      return href;
    }

    const pathnameWithoutLocale = href.replace(urlLocaleMatcherRegex, '');
    const hrefWithLocale = `/${locale}${pathnameWithoutLocale}`;

    if (localeUrlStrategy === LocaleUrlStrategy.ShowAllLocales) {
      return hrefWithLocale;
    } else if (
      localeUrlStrategy === LocaleUrlStrategy.HideDefaultLocale &&
      locale !== defaultLocaleValue
    ) {
      return hrefWithLocale;
    }

    return href || '#';
  }, [href, defaultLocaleValue, locale, localeUrlStrategy]);

  return (
    <NextLink href={formattedHref} {...rest}>
      {children}
    </NextLink>
  );
};
