import React, { useContext, useEffect } from "react";
import classnames from "classnames";
import { FormGroupContext } from "../FormGroup/FormGroupContext";
import { bem } from "../../utilities";
import { THEME } from "../../types";

export interface LabelProps extends React.HTMLProps<HTMLLabelElement> {
  hideRequiredStyles?: boolean;
  isRequired?: boolean;
  theme?: THEME;
}

const cn = "Label";

export const Label = (props: LabelProps) => {
  const {
    className,
    htmlFor: htmlForProp,
    children,
    hideRequiredStyles = false,
    isRequired = undefined,
    theme: themeProp,
    ...rest
  } = props;
  const {
    id: idContext,
    isRequired: isRequiredContext,
    theme: themeContext,
    setHasLabel,
    labelProps: labelPropsContext,
  } = useContext(FormGroupContext);

  useEffect(() => {
    if (setHasLabel) {
      setHasLabel(true);
    }
  }, [setHasLabel]);

  let calculatedRequired = false;
  if (isRequired !== undefined) {
    calculatedRequired = isRequired;
  } else if (isRequiredContext !== undefined) {
    calculatedRequired = isRequiredContext;
  }

  const htmlFor = idContext || htmlForProp;
  const theme = themeProp || themeContext;

  return (
    <label
      className={classnames(bem(cn), bem(cn, { m: theme }), className)}
      htmlFor={htmlFor}
      {...rest}
      {...labelPropsContext}
    >
      {children}
      {calculatedRequired && !hideRequiredStyles && (
        <span className="text-failure">*</span>
      )}
    </label>
  );
};
