import * as React from 'react';
import { useContext } from 'react';
import { Link as ReactLink } from 'react-router-dom';

import { ThemeDataContext } from '@redocly/theme/core/contexts';

export type LinkProps = {
  to: string;
  target?: '_self' | '_blank';
  external?: boolean;
  className?: string;
  style?: React.CSSProperties;
  innerRef?: React.Ref<HTMLAnchorElement>;
  languageInsensitive?: boolean;
  onClick?: () => void;
  [key: string]: unknown;
};

export function Link(props: React.PropsWithChildren<LinkProps>): JSX.Element {
  const context = useContext(ThemeDataContext);

  if (context?.components) {
    const { LinkComponent } = context.components;
    return <LinkComponent {...props} />;
  } else {
    const {
      active: _,
      httpVerb: _1,
      hasActiveSubItem: _2,
      routeSlug: _3,
      external: _4,
      innerRef,
      ...filteredProps
    } = props;

    // We omit "active" property to avoid "Warning: Received `false` for a non-boolean attribute `active`."
    return <ReactLink ref={innerRef} {...filteredProps} />;
  }
}
