"use strict";

var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault");

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

var _objectSpread2 = _interopRequireDefault(require("@babel/runtime/helpers/objectSpread2"));

var _slicedToArray2 = _interopRequireDefault(require("@babel/runtime/helpers/slicedToArray"));

var _defineProperty2 = _interopRequireDefault(require("@babel/runtime/helpers/defineProperty"));

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

var _AdapterDayjs = require("@mui/x-date-pickers/AdapterDayjs");

var _xDatePickers = require("@mui/x-date-pickers");

var _reactIntl = require("react-intl");

var _dayjs = _interopRequireDefault(require("dayjs"));

require("dayjs/locale/fi");

require("dayjs/locale/en-gb");

require("dayjs/locale/sv");

var _dateFns = require("date-fns");

var _utils = require("../../../utils");

var _Button = _interopRequireDefault(require("@material-ui/core/Button"));

var _styles = require("@material-ui/core/styles");

var _rjsfCore = require("@visma/rjsf-core");

var _core = require("@material-ui/core");

var _jsxRuntime = require("react/jsx-runtime");

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

var useStyles = (0, _styles.makeStyles)(function (theme) {
  return {
    button: (0, _defineProperty2["default"])({
      marginRight: theme.spacing(1),
      marginLeft: theme.spacing(1)
    }, theme.breakpoints.down('xs'), {
      marginTop: theme.spacing(1),
      marginLeft: '0px'
    }),
    dateBox: (0, _defineProperty2["default"])({
      display: 'flex',
      alignItems: 'center'
    }, theme.breakpoints.down('xs'), {
      flexDirection: 'column',
      alignItems: 'start'
    })
  };
});

var getDefaultValue = function getDefaultValue(_ref) {
  var type = _ref.type,
      defaultValue = _ref.defaultValue,
      limitType = _ref.limitType,
      limitAmount = _ref.limitAmount;

  switch (type) {
    case 'noDefault':
      return null;

    case 'today':
      return (0, _dayjs["default"])();

    case 'fixed':
      return (0, _dayjs["default"])(defaultValue);

    case 'limit':
      return limitAmount < 0 ? beforeDay({
        type: limitType,
        numberValue: limitAmount * -1
      }) : afterDay({
        type: limitType,
        numberValue: limitAmount
      });
  }

  return null;
};

var beforeDay = function beforeDay(disableBefore) {
  if ((disableBefore === null || disableBefore === void 0 ? void 0 : disableBefore.type) && (disableBefore === null || disableBefore === void 0 ? void 0 : disableBefore.type) !== 'noValue') {
    return (0, _dayjs["default"])(disableBefore.type !== 'date' ? (0, _dateFns.sub)(new Date(), (0, _defineProperty2["default"])({}, disableBefore.type, disableBefore.numberValue)) : disableBefore.dateValue);
  } else {
    return null;
  }
};

var afterDay = function afterDay(disableAfter) {
  if ((disableAfter === null || disableAfter === void 0 ? void 0 : disableAfter.type) && (disableAfter === null || disableAfter === void 0 ? void 0 : disableAfter.type) !== 'noValue') {
    return (0, _dayjs["default"])(disableAfter.type !== 'date' ? (0, _dateFns.add)(new Date(), (0, _defineProperty2["default"])({}, disableAfter.type, disableAfter.numberValue)) : disableAfter.dateValue);
  } else {
    return null;
  }
};

function BasicDatePicker(props) {
  var _props$options$dateFo, _props$options;

  var onChange = props.onChange,
      options = props.options;

  var _React$useState = React.useState(null),
      _React$useState2 = (0, _slicedToArray2["default"])(_React$useState, 2),
      value = _React$useState2[0],
      setValue = _React$useState2[1];

  var intl = (0, _reactIntl.useIntl)();
  var locale = intl.locale;

  var _options$element = options === null || options === void 0 ? void 0 : options.element,
      disableBefore = _options$element.disableBefore,
      disableAfter = _options$element.disableAfter;

  var classes = useStyles();
  var isDesktop = (0, _core.useMediaQuery)('@media (pointer: fine)');
  var ariaLabel = (0, _utils.getAriaLabel)(props.label, props.options, props.required, intl.formatMessage({
    id: "l4R23W",
    defaultMessage: [{
      "type": 0,
      "value": "Pakollinen kenttä"
    }]
  }));
  var ariaDaySelected = intl.formatMessage({
    id: "DTBNqp",
    defaultMessage: [{
      "type": 0,
      "value": "Valitse päivä, valittu päivä on"
    }]
  });
  var ariaNoSelection = intl.formatMessage({
    id: "QqAI08",
    defaultMessage: [{
      "type": 0,
      "value": "Valitse päivä"
    }]
  });
  var ariaToUse = value ? "".concat(ariaDaySelected, " ").concat(value === null || value === void 0 ? void 0 : value.format('YYYY-MM-DD')) : ariaNoSelection;

  var handleLocaleText = function handleLocaleText() {
    if (locale === 'fi-FI') {
      var _fiFI$components, _fiFI$components$MuiL, _fiFI$components$MuiL2;

      return _xDatePickers.fiFI === null || _xDatePickers.fiFI === void 0 ? void 0 : (_fiFI$components = _xDatePickers.fiFI.components) === null || _fiFI$components === void 0 ? void 0 : (_fiFI$components$MuiL = _fiFI$components.MuiLocalizationProvider) === null || _fiFI$components$MuiL === void 0 ? void 0 : (_fiFI$components$MuiL2 = _fiFI$components$MuiL.defaultProps) === null || _fiFI$components$MuiL2 === void 0 ? void 0 : _fiFI$components$MuiL2.localeText;
    } else if (locale === 'sv-SE') {
      var _svSE$components, _svSE$components$MuiL, _svSE$components$MuiL2;

      return _xDatePickers.svSE === null || _xDatePickers.svSE === void 0 ? void 0 : (_svSE$components = _xDatePickers.svSE.components) === null || _svSE$components === void 0 ? void 0 : (_svSE$components$MuiL = _svSE$components.MuiLocalizationProvider) === null || _svSE$components$MuiL === void 0 ? void 0 : (_svSE$components$MuiL2 = _svSE$components$MuiL.defaultProps) === null || _svSE$components$MuiL2 === void 0 ? void 0 : _svSE$components$MuiL2.localeText;
    }
  };

  (0, React.useEffect)(function () {
    setValue((props === null || props === void 0 ? void 0 : props.value) ? (0, _dayjs["default"])(props === null || props === void 0 ? void 0 : props.value) : options.dateDefault ? getDefaultValue(options.dateDefault) : null);
  }, []);
  (0, React.useEffect)(function () {
    setTimeout(function () {
      onChange(value === null || value === void 0 ? void 0 : value.format('YYYY-MM-DD'));
    });
  }, [value]);
  return /*#__PURE__*/(0, _jsxRuntime.jsx)(_xDatePickers.LocalizationProvider, {
    dateAdapter: _AdapterDayjs.AdapterDayjs,
    adapterLocale: locale.split('-')[0].toString(),
    localeText: handleLocaleText(),
    children: /*#__PURE__*/(0, _jsxRuntime.jsxs)("div", {
      className: classes.dateBox,
      children: [/*#__PURE__*/(0, _jsxRuntime.jsx)(_xDatePickers.DatePicker, (0, _objectSpread2["default"])((0, _objectSpread2["default"])({}, (options === null || options === void 0 ? void 0 : options.dateDefault) ? {
        defaultValue: getDefaultValue(options.dateDefault)
      } : {}), {}, {
        value: value,
        label: intl.formatMessage({
          id: "xLN8SB",
          defaultMessage: [{
            "type": 0,
            "value": "Päivämäärä"
          }]
        }),
        minDate: beforeDay(disableBefore),
        maxDate: afterDay(disableAfter),
        sx: {
          maxWidth: 200,
          "& .MuiInputBase-input.Mui-disabled": {
            WebkitTextFillColor: "#000000"
          }
        },
        arialabel: ariaLabel,
        format: (_props$options$dateFo = props === null || props === void 0 ? void 0 : (_props$options = props.options) === null || _props$options === void 0 ? void 0 : _props$options.dateFormat) !== null && _props$options$dateFo !== void 0 ? _props$options$dateFo : 'D.M.YYYY',
        onChange: setValue,
        slotProps: {
          textField: {
            disabled: isDesktop,
            placeholder: '',
            'aria-describedby': _rjsfCore.utils.ariaDescribedBy(props.id, props.uiSchema, props.rawErrors)
          },
          openPickerButton: {
            'aria-label': "".concat(ariaLabel, ", ").concat(ariaToUse),
            'aria-describedby': _rjsfCore.utils.ariaDescribedBy(props.id, props.uiSchema, props.rawErrors)
          }
        }
      })), value ? /*#__PURE__*/(0, _jsxRuntime.jsx)(_Button["default"], {
        variant: "contained",
        color: "secondary",
        size: "small",
        className: classes.button,
        onClick: function onClick(value) {
          return value && props.list ? onChange([null]) : value && setValue(null);
        },
        children: /*#__PURE__*/(0, _jsxRuntime.jsx)(_reactIntl.FormattedMessage, {
          id: "fVRBN+",
          defaultMessage: [{
            "type": 0,
            "value": "Tyhjennä"
          }]
        })
      }) : /*#__PURE__*/(0, _jsxRuntime.jsx)(_jsxRuntime.Fragment, {})]
    })
  });
}

var _default = function _default(_ref2) {
  var _reviewProps$dateForm;

  var _ref2$config = _ref2.config,
      disableBefore = _ref2$config.disableBefore,
      disableAfter = _ref2$config.disableAfter,
      dateDefault = _ref2$config.dateDefault,
      reviewProps = _ref2.reviewProps;
  return {
    schema: {
      format: 'date',
      type: 'string'
    },
    uiSchema: {
      'ui:widget': BasicDatePicker,
      'ui:options': {
        disableBefore: disableBefore,
        disableAfter: disableAfter,
        dateDefault: dateDefault,
        dateFormat: reviewProps === null || reviewProps === void 0 ? void 0 : (_reviewProps$dateForm = reviewProps.dateFormat) === null || _reviewProps$dateForm === void 0 ? void 0 : _reviewProps$dateForm.replaceAll('d', 'D')
      }
    }
  };
};

exports["default"] = _default;
var name = (0, _reactIntl.defineMessage)({
  id: "xLN8SB",
  defaultMessage: [{
    "type": 0,
    "value": "Päivämäärä"
  }]
});
exports.name = name;
var elementType = 'field';
exports.elementType = elementType;
//# sourceMappingURL=index.cjs.map