'use strict';

Object.defineProperty(exports, '__esModule', { value: true });

var clsx = require('clsx');
var React = require('react');
require('../common/theme.js');
require('../common/direction.js');
require('../common/propsValues/control.js');
var breakpoint = require('../common/propsValues/breakpoint.js');
var size = require('../common/propsValues/size.js');
require('../common/propsValues/typography.js');
require('../common/propsValues/width.js');
require('../common/propsValues/type.js');
require('../common/propsValues/dateMode.js');
var monthFormat = require('../common/propsValues/monthFormat.js');
var position = require('../common/propsValues/position.js');
require('../common/propsValues/layouts.js');
require('../common/propsValues/status.js');
require('../common/propsValues/sentiment.js');
require('../common/propsValues/profileType.js');
require('../common/propsValues/variant.js');
require('../common/propsValues/scroll.js');
require('../common/propsValues/markdownNodeType.js');
require('../common/fileType.js');
require('@transferwise/icons');
require('react-intl');
require('../common/closeButton/CloseButton.messages.js');
var jsxRuntime = require('react/jsx-runtime');
require('@transferwise/formatting');
var moveToWithinRange = require('../common/dateUtils/moveToWithinRange/moveToWithinRange.js');
var isWithinRange = require('../common/dateUtils/isWithinRange/isWithinRange.js');
var getDateView = require('../common/dateUtils/getDateView/getDateView.js');
var ResponsivePanel = require('../common/responsivePanel/ResponsivePanel.js');
var contexts = require('../inputs/contexts.js');
var OverlayIdProvider = require('../provider/overlay/OverlayIdProvider.js');
var DateTrigger = require('./dateTrigger/DateTrigger.js');
var DayCalendar = require('./dayCalendar/DayCalendar.js');
var getStartOfDay = require('./getStartOfDay/getStartOfDay.js');
var MonthCalendar = require('./monthCalendar/MonthCalendar.js');
var YearCalendar = require('./yearCalendar/YearCalendar.js');

class DateLookup extends React.PureComponent {
  static defaultProps = {
    value: null,
    min: null,
    max: null,
    size: size.Size.MEDIUM,
    placeholder: '',
    label: '',
    monthFormat: monthFormat.MonthFormat.LONG,
    disabled: false,
    clearable: false
  };
  element = /*#__PURE__*/React.createRef();
  dropdown = /*#__PURE__*/React.createRef();
  constructor(props) {
    super(props);
    const dateView = getDateView.returnDateView(props.value, props.min, props.max);
    this.state = {
      selectedDate: getStartOfDay.getStartOfDay(props.value),
      originalDate: null,
      min: getStartOfDay.getStartOfDay(props.min),
      max: getStartOfDay.getStartOfDay(props.max),
      viewMonth: dateView.getMonth(),
      viewYear: dateView.getFullYear(),
      open: false,
      mode: 'day',
      isMobile: false
    };
  }
  static getDerivedStateFromProps(props, state) {
    const propsSelected = getStartOfDay.getStartOfDay(props.value);
    const propsMin = getStartOfDay.getStartOfDay(props.min);
    const propsMax = getStartOfDay.getStartOfDay(props.max);
    const hasSelectedChanged = state.selectedDate?.getTime() !== propsSelected?.getTime();
    const hasMinChanged = state.min?.getTime() !== propsMin?.getTime();
    const hasMaxChanged = state.max?.getTime() !== propsMax?.getTime();
    if (hasSelectedChanged || hasMinChanged || hasMaxChanged) {
      const selectedDate = hasSelectedChanged ? propsSelected : state.selectedDate;
      const min = hasMinChanged ? propsMin : state.min;
      const max = hasMaxChanged ? propsMax : state.max;
      if (selectedDate && !isWithinRange.isWithinRange(selectedDate, min, max)) {
        props.onChange(moveToWithinRange.moveToWithinRange(selectedDate, min, max));
        return null;
      }
      const viewDateThatIsWithinRange = getDateView.returnDateView(selectedDate, min, max);
      const viewMonth = viewDateThatIsWithinRange.getMonth();
      const viewYear = viewDateThatIsWithinRange.getFullYear();
      return {
        selectedDate,
        min,
        max,
        viewMonth,
        viewYear
      };
    }
    return null;
  }
  componentDidUpdate(previousProps) {
    if (this.props.value?.getTime() !== previousProps.value?.getTime() && this.state.open) {
      this.focusOn('.active');
    }
    const mediaQuery = window.matchMedia(`(max-width: ${breakpoint.Breakpoint.SMALL}px)`);
    this.setState({
      isMobile: mediaQuery.matches
    });
  }
  componentWillUnmount() {
    // Prevents memory leak by cleaning state.
    this.setState = () => {};
  }
  open = () => {
    const {
      onFocus
    } = this.props;
    this.setState({
      open: true,
      mode: 'day'
    });
    if (onFocus) {
      onFocus();
    }
  };
  discard = () => {
    const {
      originalDate
    } = this.state;
    if (originalDate !== null) {
      this.props.onChange(originalDate);
    }
    this.close();
  };
  close = () => {
    const {
      onBlur
    } = this.props;
    this.setState({
      open: false,
      originalDate: null
    });
    if (onBlur) {
      onBlur();
    }
  };
  handleKeyDown = event => {
    const {
      open,
      originalDate
    } = this.state;
    switch (event.key) {
      case 'ArrowLeft':
        if (open) {
          this.adjustDate(-1, -1, -1);
        } else {
          this.open();
        }
        event.preventDefault();
        break;
      case 'ArrowUp':
        if (open) {
          this.adjustDate(-7, -4, -4);
        } else {
          this.open();
        }
        event.preventDefault();
        break;
      case 'ArrowRight':
        if (open) {
          this.adjustDate(1, 1, 1);
        } else {
          this.open();
        }
        event.preventDefault();
        break;
      case 'ArrowDown':
        if (open) {
          this.adjustDate(7, 4, 4);
        } else {
          this.open();
        }
        event.preventDefault();
        break;
      case 'Escape':
        if (originalDate !== null) {
          this.props.onChange(originalDate);
        }
        this.close();
        event.preventDefault();
        break;
    }
  };
  adjustDate = (daysToAdd, monthsToAdd, yearsToAdd) => {
    const {
      selectedDate,
      min,
      max,
      mode,
      originalDate
    } = this.state;
    if (originalDate === null) {
      this.setState({
        originalDate: selectedDate
      });
    }
    let date;
    if (selectedDate) {
      date = new Date(mode === 'year' ? selectedDate.getFullYear() + yearsToAdd : selectedDate.getFullYear(), mode === 'month' ? selectedDate.getMonth() + monthsToAdd : selectedDate.getMonth(), mode === 'day' ? selectedDate.getDate() + daysToAdd : selectedDate.getDate());
    } else {
      date = getStartOfDay.getStartOfDay(new Date());
    }
    date &&= moveToWithinRange.moveToWithinRange(date, min, max);
    if (date?.getTime() !== selectedDate?.getTime()) {
      this.props.onChange(date);
    }
  };
  focusOn = (preferredElement, fallbackElement) => {
    const element = this.element.current?.querySelector(preferredElement);
    if (element) {
      element.focus();
    } else if (fallbackElement) {
      this.focusOn(fallbackElement);
    }
  };
  switchMode = mode => {
    this.setState({
      mode
    }, () => {
      this.focusOn('.active', '.today');
    });
  };
  switchToDays = () => this.switchMode('day');
  switchToMonths = () => this.switchMode('month');
  switchToYears = () => this.switchMode('year');
  handleSelectedDateUpdate = selectedDate => {
    this.setState({
      selectedDate
    }, () => {
      this.props.onChange(selectedDate);
      this.close();
      this.focusOn('.btn');
    });
  };
  handleViewDateUpdate = ({
    month = this.state.viewMonth,
    year = this.state.viewYear
  }) => {
    this.setState({
      viewMonth: month,
      viewYear: year
    });
  };
  getCalendar = () => {
    const {
      selectedDate,
      min,
      max,
      viewMonth,
      viewYear,
      mode,
      isMobile
    } = this.state;
    const {
      placeholder,
      monthFormat
    } = this.props;
    return /*#__PURE__*/jsxRuntime.jsxs("div", {
      className: clsx.clsx({
        'p-a-1': !isMobile
      }),
      children: [mode === 'day' && /*#__PURE__*/jsxRuntime.jsx(DayCalendar.default, {
        selectedDate: selectedDate,
        min: min,
        max: max,
        viewMonth: viewMonth,
        viewYear: viewYear,
        monthFormat: monthFormat,
        onSelect: this.handleSelectedDateUpdate,
        onLabelClick: this.switchToYears,
        onViewDateUpdate: this.handleViewDateUpdate
      }), mode === 'month' && /*#__PURE__*/jsxRuntime.jsx(MonthCalendar.default, {
        selectedDate: selectedDate,
        min: min,
        max: max,
        viewYear: viewYear,
        placeholder: placeholder,
        onSelect: this.switchToDays,
        onLabelClick: this.switchToYears,
        onViewDateUpdate: this.handleViewDateUpdate
      }), mode === 'year' && /*#__PURE__*/jsxRuntime.jsx(YearCalendar.default, {
        selectedDate: selectedDate,
        min: min,
        max: max,
        viewYear: viewYear,
        placeholder: placeholder,
        onSelect: this.switchToMonths,
        onViewDateUpdate: this.handleViewDateUpdate
      })]
    });
  };
  handleClear = () => {
    this.props.onChange(null);
    this.focusOn('.np-date-trigger');
  };
  render() {
    const {
      selectedDate,
      open
    } = this.state;
    const {
      inputAttributes,
      id: idProp,
      'aria-labelledby': ariaLabelledByProp,
      size,
      placeholder,
      label,
      monthFormat,
      disabled,
      clearable,
      value
    } = this.props;
    const id = idProp ?? inputAttributes?.id;
    const ariaLabelledBy = ariaLabelledByProp ?? inputAttributes?.['aria-labelledby'];
    return /*#__PURE__*/jsxRuntime.jsx("div", {
      ref: this.element,
      "aria-labelledby": id,
      "aria-invalid": inputAttributes?.['aria-invalid'],
      "aria-describedby": inputAttributes?.['aria-describedby'],
      className: "input-group",
      onKeyDown: this.handleKeyDown,
      children: /*#__PURE__*/jsxRuntime.jsxs(OverlayIdProvider.OverlayIdProvider, {
        open: open,
        children: [/*#__PURE__*/jsxRuntime.jsx(DateTrigger.default, {
          id: id,
          ariaLabelledBy: ariaLabelledBy,
          selectedDate: selectedDate,
          size: size,
          placeholder: placeholder,
          label: label,
          monthFormat: monthFormat,
          disabled: disabled || false,
          onClick: this.open,
          onClear: !disabled && clearable && value ? this.handleClear : undefined
        }), /*#__PURE__*/jsxRuntime.jsx(ResponsivePanel.default, {
          anchorRef: this.element,
          open: open,
          className: "tw-date-lookup-menu",
          position: position.Position.BOTTOM,
          considerHeight: true,
          onClose: this.discard,
          children: this.getCalendar()
        })]
      })
    });
  }
}
const WrappedDateLookup = contexts.withInputAttributes(DateLookup, {
  nonLabelable: true
});
WrappedDateLookup.displayName = 'DateLookup';

exports.default = WrappedDateLookup;
//# sourceMappingURL=DateLookup.js.map
