import * as React from 'react';
import { useContext } from 'react';
import { Link as ReactLink } from 'react-router-dom';
import isPropValid from '@emotion/is-prop-valid';

import type { JSX } from 'react';
import type { RelativeRoutingType } from 'react-router-dom';

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

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

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 {
      innerRef,
      to,
      external: _external,
      languageInsensitive: _languageInsensitive,
      reloadDocument,
      replace,
      state,
      preventScrollReset,
      relative,
      viewTransition,
      ...restProps
    } = props;
    const linkProps = Object.fromEntries(
      Object.entries(restProps).filter(([key, value]) => value !== undefined && isPropValid(key)),
    );

    return (
      <ReactLink
        ref={innerRef}
        to={to}
        reloadDocument={reloadDocument}
        replace={replace}
        state={state}
        preventScrollReset={preventScrollReset}
        relative={relative}
        viewTransition={viewTransition}
        {...linkProps}
      />
    );
  }
}
