import React, { useCallback, useContext } from 'react';

import type { ComponentProps, ReactElement } from 'react';

import { MarkdownLinkContext } from '@redocly/theme/core/contexts';
import { Link } from '@redocly/theme/components/Link/Link';

type MarkdownLinkProps = Omit<ComponentProps<typeof Link>, 'to' | 'onClick'> & {
  href: string;
};

export function MarkdownLink({ href, ...props }: MarkdownLinkProps): ReactElement {
  const markdownLinkContext = useContext(MarkdownLinkContext);
  const onClick = useCallback(() => {
    markdownLinkContext?.onMarkdownLinkClick?.(href);
  }, [markdownLinkContext, href]);

  const linkProps = { ...props, languageInsensitive: true, onClick };

  return <Link to={href} {...linkProps} />;
}
