import React, { forwardRef, useContext } from "react";
import classNames from "classnames";
import { bem } from "../../utilities/bem";
import { STATUS_VARIANT } from "../../types";
import { StatusContext } from "../../contexts/status";

const cn = "Link";

export interface LinkProps {
  as?: any;
  noStyles?: boolean;
  statusVariant?: STATUS_VARIANT;
  [key: string]: any;
}

export const Link = forwardRef<
  HTMLAnchorElement | HTMLButtonElement | HTMLDivElement,
  LinkProps
>((props, ref) => {
  const {
    as: Component = "a",
    className,
    disabled,
    noStyles,
    statusVariant: statusVariantProp,
    target,
    ...rest
  } = props;
  const context = useContext(StatusContext);
  const calculatedVariant = statusVariantProp || context;

  const classes = classNames(
    !noStyles && bem(cn),
    calculatedVariant && bem(cn, { m: calculatedVariant }),
    disabled && "isDisabled",
    className,
  );

  return (
    <Component
      className={classes}
      disabled={Component === "button" && disabled}
      target={target}
      rel={`${target === "_blank" ? "noopener noreferrer" : ""}`}
      ref={ref}
      {...rest}
    />
  );
});
