import _extends from "@babel/runtime/helpers/esm/extends";
import _inheritsLoose from "@babel/runtime/helpers/esm/inheritsLoose";
var _dec, _class, _DatePicker;
import React from 'react';
import { Popup } from "../../../internal/Popup";
import { LocaleContext } from "../../../lib/locale";
import { locale } from "../../../lib/locale/decorators";
import { InternalDateGetter } from "../../../lib/date/InternalDateGetter";
import { ArrowAUpIcon16Light } from "../../../internal/icons2022/ArrowAUpIcon/ArrowAUp16Light";
import { ThemeFactory } from "../../../lib/theming/ThemeFactory";
import { InternalDate } from "../../../lib/date/InternalDate";
import { MAX_FULLDATE, MIN_FULLDATE } from "../../../lib/date/constants";
import { InternalDateOrder, InternalDateSeparator, InternalDateValidateCheck } from "../../../lib/date/types";
import { DateInput } from "../../DateInput";
import { filterProps } from "../../../lib/filterProps";
import { CommonWrapper } from "../../../internal/CommonWrapper";
import { isMobile } from "../../../lib/client";
import { NativeDateInput } from "../../../internal/NativeDateInput";
import { getRootNode, rootNode } from "../../../lib/rootNode";
import { isNonNullable } from "../../../lib/utils";
import { createPropsGetter } from "../../../lib/createPropsGetter";
import { Calendar } from "../../Calendar";
import { ThemeContext } from "../../../lib/theming/ThemeContext";
import { Button } from "../../Button";
import { getTodayDate } from "../../Calendar/CalendarUtils";
import { responsiveLayout } from "../../ResponsiveLayout/decorator";
import { getMenuPositions } from "../../../lib/getMenuPositions";
import { ZIndex } from "../../../internal/ZIndex";
import { styles } from "../DatePicker.styles";
import { DatePickerLocaleHelper } from "../locale";
import { MobilePicker } from "../MobilePicker";
var INPUT_PASS_PROPS = {
  autoFocus: true,
  disabled: true,
  warning: true,
  error: true,
  size: true,
  onKeyDown: true
};
export var MIN_WIDTH = 120;
export var DatePickerDataTids = {
  root: 'DatePicker__root',
  input: 'DatePicker__input',
  label: 'DatePicker__label',
  pickerRoot: 'Picker__root',
  pickerTodayWrapper: 'Picker__todayWrapper'
};

/**
 * Поле `DatePicker` помогает вводить дату с клавиатуры или выбирать ее с помощью мыши.
 *
 * Используйте поле с датой, когда нужно ввести дату в формате ДД.ММ.ГГГГ.
 *
 * Поле с датой отличается от обычного поля ввода наличием иконки, маски и блока календаря.
 */
export var DatePicker = (_dec = locale('DatePicker', DatePickerLocaleHelper), responsiveLayout(_class = rootNode(_class = _dec(_class = (_DatePicker = /*#__PURE__*/function (_React$PureComponent) {
  function DatePicker() {
    var _this;
    for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) {
      args[_key] = arguments[_key];
    }
    _this = _React$PureComponent.call.apply(_React$PureComponent, [this].concat(args)) || this;
    _this.getProps = createPropsGetter(DatePicker.defaultProps);
    _this.canOpenPopup = true;
    _this.state = {
      opened: false,
      canUseMobileNativeDatePicker: false,
      today: getTodayDate()
    };
    _this.input = null;
    _this.focused = false;
    _this.renderMain = function (props) {
      var picker = null;
      var _this$getProps = _this.getProps(),
        minDate = _this$getProps.minDate,
        maxDate = _this$getProps.maxDate,
        menuPos = _this$getProps.menuPos,
        menuAlign = _this$getProps.menuAlign;
      var isMobile = _this.isMobileLayout;
      if (_this.state.opened) {
        if (isMobile) {
          picker = /*#__PURE__*/
          React.createElement(MobilePicker, {
            value: _this.props.value,
            minDate: _this.parseValueToDate(minDate),
            maxDate: _this.parseValueToDate(maxDate),
            onValueChange: _this.props.onValueChange,
            enableTodayLink: _this.props.enableTodayLink,
            isHoliday: _this.props.isHoliday,
            onCloseRequest: _this.handleMobileCloseRequest,
            renderDay: props.renderDay,
            onMonthChange: props.onMonthChange
          });
        } else {
          picker = /*#__PURE__*/
          React.createElement(LocaleContext.Provider, {
            value: {
              locale: {
                Calendar: {
                  months: _this.locale.months,
                  dayCellChooseDateAriaLabel: _this.locale.dayCellChooseDateAriaLabel,
                  selectMonthAriaLabel: _this.locale.selectMonthAriaLabel,
                  selectYearAriaLabel: _this.locale.selectYearAriaLabel,
                  selectChosenAriaLabel: _this.locale.selectChosenAriaLabel
                }
              }
            }
          }, /*#__PURE__*/

          React.createElement(Popup, {
            opened: true,
            hasShadow: true,
            priority: ZIndex.priorities.PopupMenu,
            positions: getMenuPositions(menuPos, menuAlign),
            "data-tid": DatePickerDataTids.root,
            anchorElement: _this.getParent(),
            margin: parseInt(_this.theme.datePickerMenuOffsetY)
          }, /*#__PURE__*/

          React.createElement("div", {
            "data-tid": DatePickerDataTids.pickerRoot,
            className: styles.calendarWrapper(_this.theme),
            onMouseDown: function onMouseDown(e) {
              return e.preventDefault();
            }
          }, /*#__PURE__*/

          React.createElement(Calendar, {
            maxDate: _this.parseValueToDate(maxDate),
            minDate: _this.parseValueToDate(minDate),
            onValueChange: _this.handleValueChange,
            isHoliday: _this.props.isHoliday,
            value: _this.parseValueToDate(_this.props.value),
            renderDay: _this.props.renderDay,
            onMonthChange: _this.props.onMonthChange
          }), _this.props.enableTodayLink && _this.renderTodayLink(), ' ')));
        }
      }
      return /*#__PURE__*/(
        React.createElement("label", {
          className: styles.root(),
          style: _this.getRootStyle(),
          onMouseEnter: _this.props.onMouseEnter,
          onMouseLeave: _this.props.onMouseLeave,
          onMouseOver: _this.props.onMouseOver,
          "data-tid": DatePickerDataTids.label
        }, /*#__PURE__*/

        React.createElement(DateInput, _extends({
          id: _this.props.id
        }, filterProps(props, INPUT_PASS_PROPS), {
          ref: _this.getInputRef,
          value: _this.props.value || '',
          width: "100%",
          withIcon: true,
          minDate: minDate,
          maxDate: maxDate,
          onBlur: isMobile ? undefined : _this.handleBlur,
          onFocus: _this.handleFocus,
          onValueChange: _this.props.onValueChange,
          onClick: _this.openPickerPopup,
          onKeyDown: _this.handleKeyDown,
          "data-tid": DatePickerDataTids.input
        })), _this.state.canUseMobileNativeDatePicker ? /*#__PURE__*/
        React.createElement(NativeDateInput, {
          onValueChange: _this.props.onValueChange,
          value: _this.props.value || '',
          minDate: minDate,
          maxDate: maxDate,
          disabled: _this.props.disabled
        }) : picker)
      );
    };
    _this.getParent = function () {
      return getRootNode(_this);
    };
    _this.getRootStyle = function () {
      var width = _this.props.width;
      return isNonNullable(width) ? {
        width: width
      } : {
        minWidth: MIN_WIDTH
      };
    };
    _this.getInputRef = function (ref) {
      _this.input = ref;
    };
    _this.openPickerPopup = function () {
      _this.setState({
        opened: true
      });
    };
    _this.handleFocus = function () {
      if (_this.focused) {
        return;
      }
      if (!_this.canOpenPopup) {
        _this.canOpenPopup = true;
      } else {
        _this.openPickerPopup();
      }
      _this.focused = true;
      if (_this.props.onFocus) {
        _this.props.onFocus();
      }
    };
    _this.handleKeyDown = function (e) {
      if (!_this.state.opened) {
        _this.openPickerPopup();
      }
      if (_this.props.onKeyDown) {
        _this.props.onKeyDown(e);
      }
    };
    _this.handleBlur = function () {
      if (!_this.focused) {
        return;
      }
      _this.focused = false;
      _this.close();
      if (_this.props.onBlur) {
        _this.props.onBlur();
      }
    };
    _this.handleValueChange = function (value) {
      _this.handleSelect(value);
      _this.blur();
    };
    _this.handleSelect = function (value) {
      if (!value) {
        return null;
      }
      if (_this.props.onValueChange) {
        _this.props.onValueChange(value);
      }
    };
    _this.handleMobileCloseRequest = function () {
      _this.close();
    };
    return _this;
  }
  _inheritsLoose(DatePicker, _React$PureComponent);
  var _proto = DatePicker.prototype;
  _proto.componentDidMount = function componentDidMount() {
    if (this.props.useMobileNativeDatePicker && isMobile) {
      this.setState({
        canUseMobileNativeDatePicker: true
      });
    }
    if (this.props.autoFocus) {
      this.focus();
    }
  };
  _proto.componentDidUpdate = function componentDidUpdate(prevProps, prevState) {
    var disabled = this.props.disabled;
    var opened = this.state.opened;
    if (disabled && opened) {
      this.close();
    }
    if (prevState.opened && !opened && this.isMobileLayout) {
      this.handleBlur();
    }
  } /**
    * @public
    */;
  _proto.blur = function blur() {
    if (this.input) {
      this.input.blur();
    }
    this.handleBlur();
  } /**
    * @public
    */;
  _proto.focus = function focus(opts) {
    if (this.props.disabled) {
      return;
    }
    if (opts != null && opts.withoutOpenDropdown) {
      this.canOpenPopup = false;
    }
    if (this.input) {
      this.input.focus();
    }
  } /**
    * Закрывает выпадашку выбора дня
    * @public
    */;
  _proto.close = function close() {
    this.setState({
      opened: false
    });
  };
  _proto.render = function render() {
    var _this2 = this;
    return /*#__PURE__*/React.createElement(ThemeContext.Consumer, null, function (theme) {
      _this2.theme = theme;
      return /*#__PURE__*/React.createElement(ThemeContext.Provider, {
        value: ThemeFactory.create({
          calendarBottomSeparatorBorder: 'none'
        }, theme)
      }, /*#__PURE__*/React.createElement(CommonWrapper, _extends({
        rootNodeRef: _this2.setRootNode
      }, _this2.getProps()), _this2.renderMain));
    });
  };
  _proto.parseValueToDate = function parseValueToDate(value) {
    if (value === undefined || value === null) {
      return undefined;
    }
    var date = new InternalDate({
      value: value
    });
    if (date.validate({
      checks: [InternalDateValidateCheck.NotNull, InternalDateValidateCheck.Native]
    })) {
      return date.toString({
        withPad: true
      });
    }
    return undefined;
  };
  _proto.renderTodayLink = function renderTodayLink() {
    var _this3 = this;
    var _this$locale = this.locale,
      order = _this$locale.order,
      separator = _this$locale.separator;
    var today = new InternalDate({
      order: order,
      separator: separator
    }).setComponents(InternalDateGetter.getTodayComponents()).toString({
      withPad: true,
      withSeparator: true
    });
    return /*#__PURE__*/React.createElement("div", {
      style: {
        margin: 8
      }
    }, /*#__PURE__*/React.createElement(Button, {
      "aria-label": this.locale.todayAriaLabel,
      "data-tid": DatePickerDataTids.pickerTodayWrapper,
      width: "100%",
      onClick: function onClick() {
        _this3.handleSelect(today);
      },
      icon: /*#__PURE__*/React.createElement(ArrowAUpIcon16Light, null)
    }, this.locale.today));
  };
  return DatePicker;
}(React.PureComponent), _DatePicker.__KONTUR_REACT_UI__ = 'DatePicker', _DatePicker.displayName = 'DatePicker', _DatePicker.defaultProps = {
  minDate: MIN_FULLDATE,
  maxDate: MAX_FULLDATE
}, _DatePicker.validate = function (value, range) {
  if (range === void 0) {
    range = {};
  }
  if (!value) {
    return false;
  }
  var _range = range,
    _range$minDate = _range.minDate,
    minDate = _range$minDate === void 0 ? MIN_FULLDATE : _range$minDate,
    _range$maxDate = _range.maxDate,
    maxDate = _range$maxDate === void 0 ? MAX_FULLDATE : _range$maxDate;
  var internalDate = new InternalDate({
    order: InternalDateOrder.DMY,
    separator: InternalDateSeparator.Dot
  }).setRangeStart(new InternalDate({
    value: minDate
  })).setRangeEnd(new InternalDate({
    value: maxDate
  })).parseValue(value);
  return internalDate.validate({
    checks: [InternalDateValidateCheck.NotNull, InternalDateValidateCheck.Number, InternalDateValidateCheck.Native, InternalDateValidateCheck.Limits, InternalDateValidateCheck.Range]
  });
}, _DatePicker)) || _class) || _class) || _class);