import "./style.pcss";

import { useEffect, useState } from "react";
import type { ReactElement, FC } from "react";
import type { ILabel } from "./config/types";
import type { IComponentBaseProps } from "../../types/components";
import { useCN } from "../../utils/react/useCN";

/**
 * Компонент лейбла для поля ввода
 * @returns {ReactElement}
 */
const Label: FC<IComponentBaseProps & ILabel> = ({
  baseClass = "formLabel",
  extraClasses = {},
  htmlFor,
  label = "",
  onClick,
  children,
  title,
  extraAttrs = {},
  isRequired,
}): ReactElement => {

  const { getCN } = useCN(baseClass);

  const [ isRequiredState, setIsRequiredState ] = useState<boolean>(!!isRequired);

  useEffect(() => {
    setIsRequiredState(!!isRequired);
  }, [ isRequired ]);

  const modificators = { isRequired: isRequiredState, ...extraClasses };

  return (
    <label title={title} onClick={onClick} className={getCN("", modificators)}
      htmlFor={htmlFor} {...extraAttrs}>
      {children || <span className={getCN("label")}>{label}</span>}
    </label>
  );

};

export type { ILabel };
export { Label };
