import React from 'react';
import LinkBase, { LinkBaseProps } from '@digigov/react-core/LinkBase';
export interface LinkComponentContextProps {
  component: React.ElementType<LinkProps>;
  children?: React.ReactNode;
}

export const CommonLink: React.FC<LinkProps> = (props) => {
  const defaultStyle = !props.className;
  const underline = props.className ? !defaultStyle : defaultStyle;
  return (
    <LinkBase defaultStyle={defaultStyle} underline={underline} {...props}>
      {props.children}
    </LinkBase>
  );
};

const LinkComponentContext =
  React.createContext<React.ElementType<LinkProps>>(CommonLink);
export const LinkProvider: React.FC<LinkComponentContextProps> = (props) => {
  return (
    <LinkComponentContext.Provider value={props.component}>
      {props.children}
    </LinkComponentContext.Provider>
  );
};

export type LinkProps = Omit<LinkBaseProps, 'ref'> &
  React.RefAttributes<HTMLAnchorElement>;

const Link: React.ExoticComponent<LinkProps> = React.forwardRef(function Link(
  { children, href = '', ...props },
  ref: React.Ref<HTMLAnchorElement>
) {
  const LinkComponent = React.useContext(LinkComponentContext) as any;
  return (
    <LinkComponent ref={ref} href={href} {...props}>
      {children}
    </LinkComponent>
  );
});
//@ts-ignore
Link.displayName = 'Link';
export default Link;
export { Link, LinkBase };
