// https://gist.github.com/necolas/f9034091723f1b279be86c7429eb0c96
import NextLink from "next/link";
import React, { Children } from "react";

import { getRouteProps, RouteParams } from "../../services/Router";

type Props = {
  activeOpacity?: number;
  children: React.ReactNode;
  /** Open link in a new window in web. (Only works when using `href`) */
  external?: boolean;
  href?: string;
  params?: RouteParams;
  replace?: boolean;
  route?: string;
  /** If false, do not scroll to top after navigating. Default `true` */
  scroll?: boolean;
  shallow?: boolean;
  reset?: boolean;
};

const Link = ({
  activeOpacity,
  params,
  route,
  children,
  external,
  href,
  replace,
  scroll,
  shallow,
  ...props
}: Props) => {
  const child: any = Children.only(children);
  const styleAsLink = child.type?.displayName === "Text";

  if (href) {
    return React.cloneElement(child, {
      accessibilityRole: "link",
      href,
      ...(styleAsLink ? { as: "a" } : {}),
      ...(external ? { hrefAttrs: { rel: "noopener", target: "_blank" } } : {}),
    });
  }

  return (
    <NextLink
      replace={replace}
      scroll={scroll}
      shallow={shallow}
      {...getRouteProps(route, params)}
      passHref
    >
      {React.cloneElement(child, {
        accessibilityRole: "link",
        ...(styleAsLink ? { as: "a" } : {}),
      })}
    </NextLink>
  );
};

export default Link;
