"use strict";

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

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

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

var _moment = _interopRequireDefault(require("moment"));

var _reactDates = require("react-dates");

var _ = require("..");

var _images = require("../../assets/images");

require("react-dates/lib/css/_datepicker.css");

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

function _getRequireWildcardCache() { if (typeof WeakMap !== "function") return null; var cache = new WeakMap(); _getRequireWildcardCache = function _getRequireWildcardCache() { return cache; }; return cache; }

function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } if (obj === null || _typeof(obj) !== "object" && typeof obj !== "function") { return { default: obj }; } var cache = _getRequireWildcardCache(); if (cache && cache.has(obj)) { return cache.get(obj); } var newObj = {}; var hasPropertyDescriptor = Object.defineProperty && Object.getOwnPropertyDescriptor; for (var key in obj) { if (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 _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) { if (typeof Symbol === "undefined" || !(Symbol.iterator in Object(arr))) return; var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_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 ownKeys(object, enumerableOnly) { var keys = Object.keys(object); if (Object.getOwnPropertySymbols) { var symbols = Object.getOwnPropertySymbols(object); if (enumerableOnly) symbols = symbols.filter(function (sym) { return Object.getOwnPropertyDescriptor(object, sym).enumerable; }); keys.push.apply(keys, symbols); } return keys; }

function _objectSpread(target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i] != null ? arguments[i] : {}; if (i % 2) { ownKeys(Object(source), true).forEach(function (key) { _defineProperty(target, key, source[key]); }); } else if (Object.getOwnPropertyDescriptors) { Object.defineProperties(target, Object.getOwnPropertyDescriptors(source)); } else { ownKeys(Object(source)).forEach(function (key) { Object.defineProperty(target, key, Object.getOwnPropertyDescriptor(source, key)); }); } } return target; }

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; }

var DateInput = function DateInput(_ref) {
  var defaultValue = _ref.defaultValue,
      onChange = _ref.onChange,
      id = _ref.id,
      label = _ref.label,
      disabled = _ref.disabled,
      optional = _ref.optional,
      status = _ref.status,
      className = _ref.className,
      _ref$hideLegend = _ref.hideLegend,
      hideLegend = _ref$hideLegend === void 0 ? false : _ref$hideLegend,
      _ref$hideField = _ref.hideField,
      hideField = _ref$hideField === void 0 ? {} : _ref$hideField;
  var commonDateInputProps = {
    className: 'oec-date-input__input margin-right-1 margin-top-0',
    disabled: disabled,
    inline: true,
    // Pass an undefined message to make text input show correct outline color, but not a redundant message
    status: status ? _objectSpread(_objectSpread({}, status), {}, {
      message: undefined
    }) : undefined,
    optional: optional,
    hideOptionalText: true
  };

  var _defaultValue = defaultValue ? _moment.default.utc(defaultValue) : undefined;

  var _useState = (0, _react.useState)(_defaultValue),
      _useState2 = _slicedToArray(_useState, 2),
      date = _useState2[0],
      setDate = _useState2[1]; // Text input values


  var _useState3 = (0, _react.useState)((_defaultValue === null || _defaultValue === void 0 ? void 0 : _defaultValue.format('M')) || ''),
      _useState4 = _slicedToArray(_useState3, 2),
      month = _useState4[0],
      setMonth = _useState4[1];

  var _useState5 = (0, _react.useState)((_defaultValue === null || _defaultValue === void 0 ? void 0 : _defaultValue.format('D')) || ''),
      _useState6 = _slicedToArray(_useState5, 2),
      day = _useState6[0],
      setDay = _useState6[1];

  var _useState7 = (0, _react.useState)((_defaultValue === null || _defaultValue === void 0 ? void 0 : _defaultValue.format('YYYY')) || ''),
      _useState8 = _slicedToArray(_useState7, 2),
      year = _useState8[0],
      setYear = _useState8[1]; // Calendar


  var _useState9 = (0, _react.useState)(false),
      _useState10 = _slicedToArray(_useState9, 2),
      calendarOpen = _useState10[0],
      setCalendarOpen = _useState10[1];

  var _useState11 = (0, _react.useState)(_defaultValue),
      _useState12 = _slicedToArray(_useState11, 2),
      calendarDate = _useState12[0],
      setCalendarDate = _useState12[1];

  (0, _react.useEffect)(function () {
    var newDate = _moment.default.utc("".concat(year, "-").concat(month, "-").concat(day), 'YYYY-MM-DD');

    if (newDate.isValid()) {
      setDate(newDate);
    }
  }, [month, day, year]);
  (0, _react.useEffect)(function () {
    if (!calendarDate) return;
    setDate(calendarDate);
    setMonth(calendarDate.format('M'));
    setDay(calendarDate.format('D'));
    setYear(calendarDate.format('YYYY'));
  }, [calendarDate]);
  (0, _react.useEffect)(function () {
    onChange(date);
  }, [onChange, date]);
  var hideMonth = hideField.month,
      hideDay = hideField.day,
      hideYear = hideField.year,
      hideCalendar = hideField.calendar;
  return /*#__PURE__*/_react.default.createElement(_.FieldSet, {
    legend: label,
    id: id,
    showLegend: !hideLegend,
    hint: "For example: ".concat((0, _moment.default)().format('M D YYYY')),
    className: className,
    status: status,
    optional: optional
  }, /*#__PURE__*/_react.default.createElement("div", {
    className: "flex-row flex-align-end usa-memorable-date"
  }, !hideMonth && /*#__PURE__*/_react.default.createElement(_.TextInput, _extends({
    value: month,
    onChange: function onChange(event) {
      var newMonth = event.target.value;
      setMonth(newMonth);
    },
    id: "".concat(id, "-month"),
    label: "Month",
    inputProps: {
      min: 1,
      max: 12,
      type: 'number'
    }
  }, commonDateInputProps)), !hideDay && /*#__PURE__*/_react.default.createElement(_.TextInput, _extends({
    value: day,
    onChange: function onChange(event) {
      var newDay = event.target.value;
      setDay(newDay);
    },
    id: "".concat(id, "-day"),
    label: "Day",
    inputProps: {
      min: 1,
      max: 31,
      type: 'number'
    }
  }, commonDateInputProps)), !hideYear && /*#__PURE__*/_react.default.createElement(_.TextInput, _extends({
    value: year,
    onChange: function onChange(event) {
      var newYear = event.target.value;
      setYear(newYear);
    },
    id: "".concat(id, "-year"),
    label: "Year",
    inputProps: {
      min: 1000,
      max: 2200,
      type: 'number'
    }
  }, commonDateInputProps)), !hideCalendar && /*#__PURE__*/_react.default.createElement("div", {
    className: "oec-calendar-dropdown oec-date-input__calendar-dropdown"
  }, /*#__PURE__*/_react.default.createElement(_.Button, {
    text: /*#__PURE__*/_react.default.createElement(_images.Calendar, {
      className: "oec-calendar-toggle__icon"
    }),
    onClick: function onClick() {
      setCalendarOpen(!calendarOpen);
    },
    title: "".concat(calendarOpen ? 'close' : 'open', " calendar"),
    className: "oec-calendar-toggle oec-calendar-dropdown__toggle"
  }), /*#__PURE__*/_react.default.createElement("div", {
    className: "oec-calendar-dropdown__calendar position-absolute z-top",
    hidden: !calendarOpen
  }, /*#__PURE__*/_react.default.createElement(_reactDates.DayPickerSingleDateController // Key forces re-render, which helps deal with bugs in this library-- see scss file
  , {
    key: JSON.stringify({
      calendarDate: calendarDate,
      calendarOpen: calendarOpen
    }),
    date: date || null,
    onDateChange: function onDateChange(newDate) {
      setCalendarDate(newDate || undefined);
    },
    focused: calendarOpen // Annoyingly this does not do anything for keyboard users
    ,
    onFocusChange: function onFocusChange(f) {
      return setCalendarOpen(f.focused || false);
    },
    onBlur: function onBlur() {
      return setCalendarOpen(false);
    } // TODO: IMPLEMENT ON TAB ONCE TYPES FOR THIS LIBRARY ARE UPDATED :/
    // onTab={() => {}}
    ,
    onOutsideClick: function onOutsideClick(e) {
      var clickOnCalendarOrButton = e.target.closest("#".concat(id, " .oec-calendar-dropdown")); // If a user clicks the button again, the button will handle closing it, and this would fire first and cause problems

      if (!clickOnCalendarOrButton) {
        setCalendarOpen(false);
      }
    },
    initialVisibleMonth: function initialVisibleMonth() {
      return date || (0, _moment.default)();
    }
  })))));
};

exports.DateInput = DateInput;