"use strict";

exports.__esModule = true;
exports.DateTime = void 0;
var _react = _interopRequireWildcard(require("react"));
var _designSystem = require("@wix/design-system");
var _Field = require("../Field");
var _dataHooks = require("../dataHooks");
var _CustomFieldsFormContext = require("../../components/CustomFieldsFormContext");
var _mobxReactLite = require("mobx-react-lite");
var _react2 = require("@wix/bex-core/react");
var _dateFns = require("date-fns");
var _datesUtil = require("../../utils/datesUtil");
var _jsxFileName = "/home/builduser/work/843658b9f44192f0/packages/cairo/dist/cjs/fields/DateTime/DateTime.tsx";
function _interopRequireWildcard(e, t) { if ("function" == typeof WeakMap) var r = new WeakMap(), n = new WeakMap(); return (_interopRequireWildcard = function (e, t) { if (!t && e && e.__esModule) return e; var o, i, f = { __proto__: null, default: e }; if (null === e || "object" != typeof e && "function" != typeof e) return f; if (o = t ? n : r) { if (o.has(e)) return o.get(e); o.set(e, f); } for (const t in e) "default" !== t && {}.hasOwnProperty.call(e, t) && ((i = (o = Object.defineProperty) && Object.getOwnPropertyDescriptor(e, t)) && (i.get || i.set) ? o(f, t, i) : f[t] = e[t]); return f; })(e, t); }
const _DateTime = ({
  dataHook,
  state,
  schema,
  initialValue,
  inputRef,
  onChange
}) => {
  const {
    environment: {
      language
    }
  } = (0, _react2.useWixPatternsContainer)();
  const rawValue = state._extendedFieldsDataMap.get(schema.id) || initialValue;
  const date = (0, _react.useMemo)(() => {
    if (!rawValue) {
      return undefined;
    }
    const d = new Date(rawValue);
    return isNaN(d.getTime()) ? undefined : d;
  }, [rawValue]);
  const [statusMessage, setStatusMessage] = (0, _react.useState)('');
  const ref = (0, _react.useRef)({});
  const dateRef = (0, _react.useRef)({});
  const timeRef = (0, _react.useRef)({});
  const [dateValue, setDateValue] = (0, _react.useState)(date == null ? void 0 : date.getDate());
  const [timeValue, setTimeValue] = (0, _react.useState)(date == null ? void 0 : date.getTime());
  const formState = (0, _CustomFieldsFormContext.useCustomFieldsFormContext)();
  (0, _react.useEffect)(() => {
    ref.current.focus = () => {
      if (dateRef.current.invalid) {
        return dateRef.current.focus == null ? void 0 : dateRef.current.focus();
      }
      return timeRef.current.focus == null ? void 0 : timeRef.current.focus();
    };
    inputRef == null || inputRef(ref.current);
  }, []);
  return /*#__PURE__*/_react.default.createElement(_Field.Field, {
    dataHook: dataHook,
    type: schema.type,
    __self: void 0,
    __source: {
      fileName: _jsxFileName,
      lineNumber: 67,
      columnNumber: 5
    }
  }, /*#__PURE__*/_react.default.createElement(_designSystem.FormField, {
    label: schema.label,
    dataHook: _dataHooks.dataHooks.Label,
    __self: void 0,
    __source: {
      fileName: _jsxFileName,
      lineNumber: 68,
      columnNumber: 7
    }
  }, /*#__PURE__*/_react.default.createElement(_designSystem.Layout, {
    __self: void 0,
    __source: {
      fileName: _jsxFileName,
      lineNumber: 69,
      columnNumber: 9
    }
  }, /*#__PURE__*/_react.default.createElement(_designSystem.Cell, {
    span: 6,
    __self: void 0,
    __source: {
      fileName: _jsxFileName,
      lineNumber: 70,
      columnNumber: 11
    }
  }, /*#__PURE__*/_react.default.createElement(_designSystem.DatePicker, {
    ref: internalRef => {
      dateRef.current.focus = () => {
        var _internalRef$state;
        return (// TODO: PR to WSR needed to expose as public API
          // @ts-expect-error
          internalRef == null || (_internalRef$state = internalRef.state) == null || (_internalRef$state = _internalRef$state.inputRef) == null || _internalRef$state.focus == null ? void 0 : _internalRef$state.focus()
        );
      };
    },
    width: "100%",
    value: date,
    locale: language
    // onChange is triggered only when you have valid, non-empty value. and onValidate is triggered on every change to we use onValidate
    ,
    onChange: () => {},
    onValidate: ({
      validationType,
      value,
      format
    }) => {
      if (validationType === 'valid') {
        const dateWithNewDate = date ? new Date(date) : new Date(value);
        const _value = (0, _dateFns.parse)(value, _datesUtil.shortDateFormats[language], new Date());
        dateWithNewDate.setFullYear(_value.getFullYear());
        dateWithNewDate.setMonth(_value.getMonth());
        dateWithNewDate.setDate(_value.getDate());
        onChange(dateWithNewDate.toISOString());
        setDateValue(new Date(value).getDate());
        setStatusMessage('');
        dateRef.current.invalid = false;
      } else if (validationType === 'formatError' && value === '') {
        setStatusMessage('');
        dateRef.current.invalid = false;
        setDateValue(value);
        if (!timeValue) {
          onChange(null);
        }
      } else {
        setStatusMessage(formState._translate('cairo.customFields.fieldType.date.invalid.value', {
          dateFormat: format ?? ''
        }));
        dateRef.current.invalid = true;
      }
      ref.current.invalid = dateRef.current.invalid || timeRef.current.invalid;
    },
    status: ref.current.invalid ? 'error' : undefined,
    statusMessage: statusMessage,
    dataHook: `${_dataHooks.dataHooks.Input}-date`,
    __self: void 0,
    __source: {
      fileName: _jsxFileName,
      lineNumber: 71,
      columnNumber: 13
    }
  })), /*#__PURE__*/_react.default.createElement(_designSystem.Cell, {
    span: 6,
    __self: void 0,
    __source: {
      fileName: _jsxFileName,
      lineNumber: 126,
      columnNumber: 11
    }
  }, /*#__PURE__*/_react.default.createElement(_designSystem.TimeInput, {
    ref: internalRef => {
      timeRef.current.focus = () => internalRef == null ? void 0 : internalRef.focus();
    },
    dataHook: `${_dataHooks.dataHooks.Input}-time`,
    value: date ?? null,
    invalidMessage: formState._translate('cairo.customFields.fieldType.dateAndTime.invalid.value'),
    onInvalid: () => {
      timeRef.current.invalid = true;
      ref.current.invalid = dateRef.current.invalid || timeRef.current.invalid;
    },
    onChange: ({
      date: newValue
    }) => {
      timeRef.current.invalid = false;
      ref.current.invalid = dateRef.current.invalid || timeRef.current.invalid;
      if (newValue) {
        const dateWithNewTime = date ? new Date(date) : newValue;
        dateWithNewTime.setHours(newValue.getHours());
        dateWithNewTime.setMinutes(newValue.getMinutes());
        dateWithNewTime.setSeconds(newValue.getSeconds());
        dateWithNewTime.setMilliseconds(newValue.getMilliseconds());
        onChange(dateWithNewTime.toISOString());
      } else if (!ref.current.invalid) {
        if (!newValue) {
          setTimeValue('');
          if (!dateValue) {
            onChange(null);
          }
        }
      }
    },
    __self: void 0,
    __source: {
      fileName: _jsxFileName,
      lineNumber: 127,
      columnNumber: 13
    }
  })))));
};
const DateTime = exports.DateTime = (0, _mobxReactLite.observer)(_DateTime);
//# sourceMappingURL=DateTime.js.map