import React, {
  useCallback,
  useContext,
  DetailedHTMLProps,
  AnchorHTMLAttributes,
  MouseEvent,
} from 'react';
import { HistoryContext } from './HistoryContext';

type Props = {
  href: string;
  replace?: boolean;
} & DetailedHTMLProps<
  AnchorHTMLAttributes<HTMLAnchorElement>,
  HTMLAnchorElement
>;

export function Link({
  href,
  onClick: onClickProp,
  children,
  replace,
  ...props
}: Props) {
  const { navigate } = useContext(HistoryContext);
  const onClick = useCallback((event: MouseEvent<HTMLAnchorElement>) => {
    event.preventDefault();
    navigate(href, replace);
    if (onClickProp !== undefined) {
      onClickProp(event);
    }
  }, [href, navigate, onClickProp, replace]);
  return <a {...props} href={href} onClick={onClick}>{children}</a>;
}
