"use strict";

function _typeof(obj) { "@babel/helpers - typeof"; return _typeof = "function" == typeof Symbol && "symbol" == typeof Symbol.iterator ? function (obj) { return typeof obj; } : function (obj) { return obj && "function" == typeof Symbol && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }, _typeof(obj); }

Object.defineProperty(exports, "__esModule", {
  value: true
});
exports.default = void 0;

var React = _interopRequireWildcard(require("react"));

var _classnames = _interopRequireDefault(require("classnames"));

var _useRadioContext = require("./useRadioContext");

var _ErrorMessage = _interopRequireDefault(require("../ErrorMessage"));

var _excluded = ["className", "children", "color", "direction", "disabled", "errorMessage", "invalid", "name", "required", "value", "onChange", "aria-labelledby", "aria-describedby"];

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

function _getRequireWildcardCache(nodeInterop) { if (typeof WeakMap !== "function") return null; var cacheBabelInterop = new WeakMap(); var cacheNodeInterop = new WeakMap(); return (_getRequireWildcardCache = function _getRequireWildcardCache(nodeInterop) { return nodeInterop ? cacheNodeInterop : cacheBabelInterop; })(nodeInterop); }

function _interopRequireWildcard(obj, nodeInterop) { if (!nodeInterop && obj && obj.__esModule) { return obj; } if (obj === null || _typeof(obj) !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(nodeInterop); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (key !== "default" && Object.prototype.hasOwnProperty.call(obj, key)) { var desc = hasPropertyDescriptor ? Object.getOwnPropertyDescriptor(obj, key) : null; if (desc && (desc.get || desc.set)) { Object.defineProperty(newObj, key, desc); } else { newObj[key] = obj[key]; } } } newObj.default = obj; if (cache) { cache.set(obj, newObj); } return newObj; }

function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); }

function _defineProperty(obj, key, value) { if (key in obj) { Object.defineProperty(obj, key, { value: value, enumerable: true, configurable: true, writable: true }); } else { obj[key] = value; } return obj; }

function _slicedToArray(arr, i) { return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); }

function _nonIterableRest() { throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); }

function _unsupportedIterableToArray(o, minLen) { if (!o) return; if (typeof o === "string") return _arrayLikeToArray(o, minLen); var n = Object.prototype.toString.call(o).slice(8, -1); if (n === "Object" && o.constructor) n = o.constructor.name; if (n === "Map" || n === "Set") return Array.from(o); if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); }

function _arrayLikeToArray(arr, len) { if (len == null || len > arr.length) len = arr.length; for (var i = 0, arr2 = new Array(len); i < len; i++) { arr2[i] = arr[i]; } return arr2; }

function _iterableToArrayLimit(arr, i) { var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"]; if (_i == null) return; var _arr = []; var _n = true; var _d = false; var _s, _e; try { for (_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true) { _arr.push(_s.value); if (i && _arr.length === i) break; } } catch (err) { _d = true; _e = err; } finally { try { if (!_n && _i["return"] != null) _i["return"](); } finally { if (_d) throw _e; } } return _arr; }

function _arrayWithHoles(arr) { if (Array.isArray(arr)) return arr; }

function _objectWithoutProperties(source, excluded) { if (source == null) return {}; var target = _objectWithoutPropertiesLoose(source, excluded); var key, i; if (Object.getOwnPropertySymbols) { var sourceSymbolKeys = Object.getOwnPropertySymbols(source); for (i = 0; i < sourceSymbolKeys.length; i++) { key = sourceSymbolKeys[i]; if (excluded.indexOf(key) >= 0) continue; if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; target[key] = source[key]; } } return target; }

function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; }

var RadioGroup = function RadioGroup(_ref) {
  var className = _ref.className,
      children = _ref.children,
      color = _ref.color,
      _ref$direction = _ref.direction,
      direction = _ref$direction === void 0 ? 'column' : _ref$direction,
      disabled = _ref.disabled,
      errorMessage = _ref.errorMessage,
      invalid = _ref.invalid,
      name = _ref.name,
      required = _ref.required,
      value = _ref.value,
      onChange = _ref.onChange,
      ariaLabelledBy = _ref['aria-labelledby'],
      ariaDescribedBy = _ref['aria-describedby'],
      props = _objectWithoutProperties(_ref, _excluded);

  var _React$useRef = React.useRef(value),
      initialValue = _React$useRef.current;

  var _React$useState = React.useState(value || null),
      _React$useState2 = _slicedToArray(_React$useState, 2),
      selectedValue = _React$useState2[0],
      setSelectedValue = _React$useState2[1];

  var _React$useState3 = React.useState(null),
      _React$useState4 = _slicedToArray(_React$useState3, 2),
      lastFocusedValue = _React$useState4[0],
      setLastFocusedValue = _React$useState4[1];

  var radioGroupClass = (0, _classnames.default)('sg-radio-group', className);
  var radioGroupItemsClass = (0, _classnames.default)('sg-radio-group__items', _defineProperty({}, "sg-radio-group__items--direction-".concat(String(direction)), direction));
  var errorTextId = name ? "".concat(name, "-errorText") : undefined;

  var _React$useState5 = React.useState(true),
      _React$useState6 = _slicedToArray(_React$useState5, 2),
      isPristine = _React$useState6[0],
      setIsPristine = _React$useState6[1]; // If value passed to RadioGroup changes, update the selectedValue


  React.useEffect(function () {
    setSelectedValue(value !== null && value !== void 0 ? value : null);
  }, [value]); // If selectedValue changes set isPristine to false

  React.useEffect(function () {
    if (selectedValue !== initialValue && isPristine) setIsPristine(false);
  }, [selectedValue, initialValue, isPristine]);

  var updateValue = function updateValue(event, value) {
    setSelectedValue(value);
    if (onChange) onChange(event);
  };

  var describedbyIds = React.useMemo(function () {
    var ids = [];

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

    if (ariaDescribedBy) {
      ids.push(ariaDescribedBy);
    }

    return ids.join(' ');
  }, [errorTextId, invalid, errorMessage, ariaDescribedBy]);
  return /*#__PURE__*/React.createElement("div", _extends({}, props, {
    className: radioGroupClass,
    role: "radiogroup" // @ts-ignore ts migration
    ,
    disabled: disabled,
    onBlur: function onBlur() {
      return setLastFocusedValue(null);
    },
    "aria-required": required,
    "aria-labelledby": ariaLabelledBy,
    "aria-describedby": describedbyIds.length ? describedbyIds : undefined
  }), /*#__PURE__*/React.createElement("div", {
    className: radioGroupItemsClass
  }, /*#__PURE__*/React.createElement(_useRadioContext.RadioContext.Provider, {
    value: {
      color: color,
      name: name,
      disabled: disabled,
      invalid: invalid,
      selectedValue: selectedValue,
      setSelectedValue: updateValue,
      lastFocusedValue: lastFocusedValue,
      setLastFocusedValue: setLastFocusedValue,
      isPristine: isPristine
    }
  }, children)), invalid && errorMessage && /*#__PURE__*/React.createElement(_ErrorMessage.default, {
    id: errorTextId,
    color: color === 'light' ? 'text-red-40' : undefined
  }, errorMessage));
};

var _default = RadioGroup;
exports.default = _default;