import _extends from "@babel/runtime/helpers/esm/extends";
import _defineProperty from "@babel/runtime/helpers/esm/defineProperty";
import _slicedToArray from "@babel/runtime/helpers/esm/slicedToArray";
import _objectWithoutProperties from "@babel/runtime/helpers/esm/objectWithoutProperties";
var _excluded = ["checked", "children", "className", "color", "defaultChecked", "description", "disabled", "errorMessage", "id", "indeterminate", "invalid", "labelSize", "required", "name", "onChange", "style", "value", "aria-labelledby"];
import * as React from 'react';
import classNames from 'classnames';
import generateRandomString from '../../../js/generateRandomString';
import { __DEV__, invariant } from '../../utils';
import Text from '../../text/Text';
import { CheckIcon, IndeterminateIcon } from './CheckboxIcon';
import ErrorMessage from '../ErrorMessage';
import { useFirstPaint } from '../../utils/useFirstPaint';

var Checkbox = function Checkbox(_ref) {
  var _classNames;

  var checked = _ref.checked,
      children = _ref.children,
      className = _ref.className,
      _ref$color = _ref.color,
      color = _ref$color === void 0 ? 'dark' : _ref$color,
      _ref$defaultChecked = _ref.defaultChecked,
      defaultChecked = _ref$defaultChecked === void 0 ? false : _ref$defaultChecked,
      description = _ref.description,
      _ref$disabled = _ref.disabled,
      disabled = _ref$disabled === void 0 ? false : _ref$disabled,
      errorMessage = _ref.errorMessage,
      id = _ref.id,
      _ref$indeterminate = _ref.indeterminate,
      indeterminate = _ref$indeterminate === void 0 ? false : _ref$indeterminate,
      _ref$invalid = _ref.invalid,
      invalid = _ref$invalid === void 0 ? false : _ref$invalid,
      _ref$labelSize = _ref.labelSize,
      labelSize = _ref$labelSize === void 0 ? 'medium' : _ref$labelSize,
      _ref$required = _ref.required,
      required = _ref$required === void 0 ? false : _ref$required,
      name = _ref.name,
      onChange = _ref.onChange,
      style = _ref.style,
      value = _ref.value,
      ariaLabelledBy = _ref['aria-labelledby'],
      props = _objectWithoutProperties(_ref, _excluded);

  var checkboxIconRef = React.useRef();

  var _React$useRef = React.useRef(id === undefined || id === '' ? generateRandomString() : id),
      checkboxId = _React$useRef.current;

  var isControlled = checked !== undefined;

  var _React$useState = React.useState(isControlled ? checked : defaultChecked),
      _React$useState2 = _slicedToArray(_React$useState, 2),
      isChecked = _React$useState2[0],
      setIsChecked = _React$useState2[1];

  var inputRef = React.useRef(null);
  var iconRef = React.useRef(null);
  var shouldAnimate = React.useRef(false);
  useFirstPaint(function () {
    shouldAnimate.current = true;
  });
  React.useEffect(function () {
    if (inputRef.current) inputRef.current.indeterminate = indeterminate;
  }, [inputRef, indeterminate]);
  React.useEffect(function () {
    if (isControlled && checked !== isChecked) {
      setIsChecked(checked);

      if (shouldAnimate.current && checkboxIconRef.current) {
        checkboxIconRef.current.classList.add('sg-checkbox__icon--with-animation');
      }
    }
  }, [checked, isControlled, isChecked]);
  var onInputChange = React.useCallback(function (e) {
    if (!isControlled) {
      setIsChecked(function (val) {
        return !val;
      });
    }

    if (onChange) onChange(e);

    if (shouldAnimate.current && checkboxIconRef.current) {
      checkboxIconRef.current.classList.add('sg-checkbox__icon--with-animation');
    }
  }, [onChange, isControlled, checkboxIconRef]);

  if (__DEV__) {
    invariant(!(errorMessage && !invalid), "Using 'errorMessage' property has no effect when 'invalid' property is not set.");
    invariant(!(errorMessage && !children), "Using 'errorMessage' property should be used along with 'children' property (label).");
  }

  var hasContent = description || invalid && errorMessage;
  var hasLabel = children !== undefined && children !== null;
  var isInputOnly = !hasLabel && !hasContent;
  var checkboxClass = classNames('sg-checkbox', className, (_classNames = {
    'sg-checkbox--disabled': disabled
  }, _defineProperty(_classNames, "sg-checkbox--".concat(String(color)), color), _defineProperty(_classNames, "sg-checkbox--with-padding", !isInputOnly), _classNames));
  var labelClass = classNames('sg-checkbox__label', _defineProperty({
    'sg-checkbox__label--with-padding-bottom': description || errorMessage
  }, "sg-checkbox__label--".concat(String(labelSize)), labelSize));
  var iconClass = classNames('sg-checkbox__icon');
  var errorTextId = "".concat(checkboxId, "-errorText");
  var descriptionId = "".concat(checkboxId, "-description");
  var describedbyIds = React.useMemo(function () {
    var ids = [];

    if (invalid && errorMessage) {
      ids.push(errorTextId);
    }

    if (description) {
      ids.push(descriptionId);
    }

    return ids.join(' ');
  }, [errorTextId, descriptionId, invalid, errorMessage, description]);
  var checkboxIcon = null;
  if (isChecked && !indeterminate) checkboxIcon = /*#__PURE__*/React.createElement(CheckIcon, {
    ref: iconRef
  });
  if (indeterminate) checkboxIcon = /*#__PURE__*/React.createElement(IndeterminateIcon, {
    ref: iconRef
  });
  React.useEffect(function () {
    requestAnimationFrame(function () {
      if (iconRef.current) {
        iconRef.current.getBoundingClientRect(); // force a reflow so checkbox icon gets painted and transition can be seen

        if (iconRef.current instanceof window.SVGElement) {
          iconRef.current.style.strokeDashoffset = '0';
        }
      }
    });
  }, [checkboxIcon]);
  return /*#__PURE__*/React.createElement("div", {
    className: checkboxClass,
    style: style
  }, /*#__PURE__*/React.createElement("div", {
    className: "sg-checkbox__wrapper"
  }, /*#__PURE__*/React.createElement("div", {
    className: "sg-checkbox__element"
  }, /*#__PURE__*/React.createElement("input", _extends({}, props, {
    ref: inputRef,
    className: "sg-checkbox__input",
    id: checkboxId,
    type: "checkbox",
    checked: isChecked,
    disabled: disabled,
    name: name,
    onChange: onInputChange,
    required: required,
    value: value,
    "aria-checked": indeterminate ? 'mixed' : isChecked,
    "aria-invalid": invalid ? true : undefined,
    "aria-describedby": describedbyIds,
    "aria-labelledby": ariaLabelledBy
  })), /*#__PURE__*/React.createElement("div", {
    className: "sg-checkbox__icon-wrapper"
  }, /*#__PURE__*/React.createElement("span", {
    className: iconClass // This element is purely decorative so
    ,
    ref: checkboxIconRef // we hide it for screen readers
    ,
    "aria-hidden": "true"
  }, checkboxIcon))), !ariaLabelledBy && hasLabel && /*#__PURE__*/React.createElement(Text, {
    htmlFor: checkboxId,
    as: "label",
    size: labelSize,
    weight: "bold",
    className: labelClass
  }, children, required && /*#__PURE__*/React.createElement("span", {
    "aria-hidden": "true"
  }, "\xA0*"))), hasContent && /*#__PURE__*/React.createElement("div", {
    className: "sg-checkbox__content"
  }, description && /*#__PURE__*/React.createElement(Text, {
    id: descriptionId,
    className: "sg-checkbox__description",
    size: "small",
    as: "span",
    breakWords: true
  }, description), invalid && errorMessage && /*#__PURE__*/React.createElement(ErrorMessage, {
    id: errorTextId,
    color: color === 'light' ? 'text-red-40' : undefined
  }, errorMessage)));
};

export default Checkbox;