import React, { Children } from "react";
import { Linking, TouchableOpacity } from "react-native";

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

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

const Link = ({
  params,
  route,
  children,
  external,
  href,
  reset,
  ...props
}: Props) => {
  const child: any = Children.only(children);
  const styleAsLink = child.type?.displayName === "Text";
  const onPress = () => {
    if (href) {
      Linking.openURL(href);
    } else {
      if (reset) {
        Router.reset(route, params);
      } else {
        Router.push(route, params);
      }
    }
  };

  if (styleAsLink) {
    return React.cloneElement(child, {
      accessibilityRole: "link",
      as: "a",
      onPress,
    });
  }

  return (
    <TouchableOpacity onPress={onPress} {...props}>
      {children}
    </TouchableOpacity>
  );
};

export default Link;
