// require (PrototypeDate.js), 使用了format
import React, { forwardRef, useRef, useImperativeHandle, useEffect } from 'react';
import Instance from './instance.js';
var Calendar = forwardRef(function (_ref, ref) {
  var _ref$type = _ref.type,
      type = _ref$type === void 0 ? 'month' : _ref$type,
      _ref$activeTo = _ref.activeTo,
      activeTo = _ref$activeTo === void 0 ? '' : _ref$activeTo,
      defaultDate = _ref.defaultDate,
      titleFormat = _ref.titleFormat,
      disableBeforeDate = _ref.disableBeforeDate,
      disableAfterDate = _ref.disableAfterDate,
      verticalDrag = _ref.verticalDrag,
      _ref$prevHTML = _ref.prevHTML,
      prevHTML = _ref$prevHTML === void 0 ? '&lt' : _ref$prevHTML,
      _ref$nextHTML = _ref.nextHTML,
      nextHTML = _ref$nextHTML === void 0 ? '&gt' : _ref$nextHTML,
      onChange = _ref.onChange,
      onClick = _ref.onClick,
      onError = _ref.onError;
  var rootRef = useRef(null);
  useImperativeHandle(ref, function () {
    return rootRef.current;
  });
  var instance = useRef(null); // 更新句柄, 防止synchronization模式, 每次组件在render的时候都生成上次render的state、function、effects

  if (instance.current) {
    instance.current.params.onChange = change;
    instance.current.params.onClick = click;
    instance.current.params.onError = onError;
  }

  function change(s) {
    if (onChange) onChange(s, s.activeDate.format('YYYY-MM-DD'), s.activeDate);
  }

  function click(s) {
    if (onClick) onClick(s, s.selectedDate.format('YYYY-MM-DD'), s.selectedDate);
  }

  useEffect(function () {
    if (instance.current) return;
    instance.current = new Instance(rootRef.current, {
      viewType: type,
      titleFormat: titleFormat,
      disableBeforeDate: disableBeforeDate,
      disableAfterDate: disableAfterDate,
      verticalDrag: verticalDrag,
      defaultDate: defaultDate,
      prevHTML: prevHTML,
      nextHTML: nextHTML,
      onChange: change,
      onClick: click,
      onError: onError // func(e, err)

    });
  }, []); // eslint-disable-line

  useEffect(function () {
    if (!instance.current) return;

    if (type === 'month') {
      instance.current.showMonth();
    } else if (type === 'week') {
      instance.current.showWeek();
    }
  }, [type]);
  useEffect(function () {
    if (!instance.current) return;

    if (activeTo instanceof Date) {
      instance.current.setDate(activeTo);
      return;
    }

    if (activeTo === 'today') {
      instance.current.setToday();
    } else if (activeTo === 'default') {
      instance.current.setDefaultDate();
    }
  }, [activeTo]);
  return /*#__PURE__*/React.createElement("div", {
    ref: rootRef,
    className: "calendar"
  });
});
export default Calendar;