'use strict';

var _defineProperty = require('@babel/runtime/helpers/defineProperty');
var _slicedToArray = require('@babel/runtime/helpers/slicedToArray');
var _objectWithoutProperties = require('@babel/runtime/helpers/objectWithoutProperties');
var React = require('react');
var dayGridPlugin = require('@fullcalendar/daygrid');
var interactionPlugin = require('@fullcalendar/interaction');
var FullCalendar = require('@fullcalendar/react');
var timeGridPlugin = require('@fullcalendar/timegrid');
var i18next = require('i18next');
var neetoCist = require('@bigbinary/neeto-cist');
var utils = require('@bigbinary/neeto-commons-frontend/utils');
var Typography = require('@bigbinary/neetoui/Typography');
var ramda = require('ramda');
var reactI18next = require('react-i18next');
var SubHeader = require('./SubHeader.js');
var injectCss = require('./inject-css-B6qYtOJe.js');
var Dropdown = require('@bigbinary/neetoui/Dropdown');
var Down = require('@bigbinary/neeto-icons/Down');
var Left = require('@bigbinary/neeto-icons/Left');
var Right = require('@bigbinary/neeto-icons/Right');
var Button = require('@bigbinary/neetoui/Button');
var DatePicker = require('@bigbinary/neetoui/DatePicker');
var jsxRuntime = require('react/jsx-runtime');
require('classnames');
require('@bigbinary/neeto-commons-frontend/react-utils');
require('@bigbinary/neeto-icons/Column');
require('./Columns-7xltEL2z.js');
require('@babel/runtime/helpers/toConsumableArray');
require('@dnd-kit/core');
require('@dnd-kit/sortable');
require('@bigbinary/neeto-icons/Search');
require('@bigbinary/neetoui/Checkbox');
require('@bigbinary/neetoui/Input');
require('@bigbinary/neetoui/Label');
require('@bigbinary/neeto-icons/Reorder');
require('@tanstack/react-query');
require('@bigbinary/neeto-commons-frontend/react-utils/useMutationWithInvalidation');
require('axios');
require('@bigbinary/neeto-icons/Download');
require('@bigbinary/neeto-filters-frontend/Filters');
require('@bigbinary/neeto-icons/Filter');

var css = ".neeto-ui-theme--light,:root{--fc-page-bg-color:#fff;--fc-neutral-bg-color:hsla(0,0%,82%,.3);--fc-border-color:#e9ebed}.neeto-ui-theme--dark{--fc-page-bg-color:#000;--fc-border-color:#2c2c2c;--fc-more-link-text-color:#000}";
injectCss.n(css,{});

var WEEKLY_VIEW = i18next.t("neetoMolecules.calendarView.weekly");
var MONTHLY_VIEW = i18next.t("neetoMolecules.calendarView.monthly");
var DAILY_VIEW = i18next.t("neetoMolecules.calendarView.daily");
var VIEW_OPTIONS = _defineProperty(_defineProperty(_defineProperty({}, DAILY_VIEW, {
  label: DAILY_VIEW,
  fullCalendarView: "timeGridDay",
  picker: "day"
}), WEEKLY_VIEW, {
  label: WEEKLY_VIEW,
  fullCalendarView: "timeGridWeek",
  picker: "week"
}), MONTHLY_VIEW, {
  label: MONTHLY_VIEW,
  fullCalendarView: "dayGridMonth",
  picker: "month"
});

var getWeekString = function getWeekString(_ref) {
  var date = _ref.date,
    _ref$isStartOfWeek = _ref.isStartOfWeek,
    isStartOfWeek = _ref$isStartOfWeek === void 0 ? true : _ref$isStartOfWeek,
    _ref$showMonth = _ref.showMonth,
    showMonth = _ref$showMonth === void 0 ? false : _ref$showMonth,
    _ref$showYear = _ref.showYear,
    showYear = _ref$showYear === void 0 ? false : _ref$showYear;
  return "".concat(showMonth || isStartOfWeek ? date.format("MMM") : "", " ").concat(date.date(), " ").concat(showYear || !isStartOfWeek ? date.format("YYYY") : "");
};
var getStartOfWeek = function getStartOfWeek(date) {
  return utils.dayjs(date).startOf("week");
};
var getEndOfWeek = function getEndOfWeek(date) {
  return utils.dayjs(date).endOf("week");
};
var getFormattedMonthStr = function getFormattedMonthStr(date) {
  return date.format("MMM YYYY");
};
var getFormattedWeekRangeStr = function getFormattedWeekRangeStr(date) {
  var startOfWeek = getStartOfWeek(date);
  var endOfWeek = getEndOfWeek(date);
  var shouldShowMonthsSeparately = startOfWeek.month() !== endOfWeek.month();
  var shouldShowYearsSeparately = startOfWeek.year() !== endOfWeek.year();
  var startOfWeekStr = getWeekString({
    date: startOfWeek,
    showMonth: shouldShowMonthsSeparately,
    showYear: shouldShowYearsSeparately
  });
  var endOfWeekStr = getWeekString({
    date: endOfWeek,
    isStartOfWeek: false,
    showMonth: shouldShowMonthsSeparately,
    showYear: shouldShowYearsSeparately
  });
  return "".concat(startOfWeekStr, " - ").concat(endOfWeekStr);
};
var getFormattedDayStr = function getFormattedDayStr(date) {
  return date.format("DD MMM YYYY");
};
var getFormattedRangeStr = function getFormattedRangeStr(date, picker) {
  var formatFunctions = {
    month: getFormattedMonthStr,
    week: getFormattedWeekRangeStr,
    day: getFormattedDayStr
  };
  var selectedFormatter = formatFunctions[picker];
  return selectedFormatter(date);
};
var mergeRefs = function mergeRefs() {
  for (var _len = arguments.length, refs = new Array(_len), _key = 0; _key < _len; _key++) {
    refs[_key] = arguments[_key];
  }
  return function (node) {
    return refs.filter(Boolean).forEach(function (ref) {
      return typeof ref === "function" ? ref(node) : ref.current = node;
    });
  };
};

var _excluded$1 = ["selectedDate", "setSelectedDate", "picker", "validDates"];
function ownKeys$1(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
function _objectSpread$1(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys$1(Object(t), true).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys$1(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
var CustomDatePicker = function CustomDatePicker(_ref) {
  var selectedDate = _ref.selectedDate,
    setSelectedDate = _ref.setSelectedDate,
    picker = _ref.picker,
    validDates = _ref.validDates,
    otherProps = _objectWithoutProperties(_ref, _excluded$1);
  var _useState = React.useState(false),
    _useState2 = _slicedToArray(_useState, 2),
    isOpen = _useState2[0],
    setIsOpen = _useState2[1];
  var datePickerRef = React.useRef(null);
  var buttonRef = React.useRef(null);
  var selectedRangeStr = getFormattedRangeStr(selectedDate, picker);
  var start = validDates.start,
    end = validDates.end;
  var isDateLessThanStart = start && selectedDate.isSameOrBefore(utils.dayjs(start), picker);
  var isDateGreaterThanEnd = end && selectedDate.isSameOrAfter(utils.dayjs(end), picker);
  var onPrevious = function onPrevious() {
    return setSelectedDate(function (selectedDate) {
      return selectedDate.subtract(1, picker);
    });
  };
  var onNext = function onNext() {
    return setSelectedDate(function (selectedDate) {
      return selectedDate.add(1, picker);
    });
  };
  var onToday = function onToday() {
    return setSelectedDate(utils.dayjs());
  };
  var getDisabledDates = function getDisabledDates(date) {
    if (!date) return false;
    return start && date <= start || end && date >= end;
  };
  var handleButtonMouseDown = function handleButtonMouseDown(e) {
    if (!(buttonRef.current && buttonRef.current.contains(e.target))) return;
    e.stopPropagation();
    if (isOpen) datePickerRef.current.focus();
  };
  return /*#__PURE__*/jsxRuntime.jsxs("div", {
    className: "flex items-center justify-start gap-x-4",
    children: [/*#__PURE__*/jsxRuntime.jsx(Button, {
      "data-testid": "neeto-molecules-calendar-view-today-button",
      label: "Today",
      style: "secondary",
      onClick: onToday
    }), /*#__PURE__*/jsxRuntime.jsxs("div", {
      className: "flex",
      children: [/*#__PURE__*/jsxRuntime.jsx(Button, {
        className: "me-1",
        "data-testid": "neeto-molecules-calendar-view-previous-button",
        disabled: isDateLessThanStart,
        icon: function icon() {
          return /*#__PURE__*/jsxRuntime.jsx(Left, {
            className: "rtl:scale-x-[-1]",
            size: 20
          });
        },
        style: "text",
        onClick: onPrevious
      }), /*#__PURE__*/jsxRuntime.jsx(Button, {
        className: "min-w-52 justify-center",
        "data-testid": "neeto-molecules-calendar-view-date-picker-button",
        icon: Down,
        ref: buttonRef,
        style: "text",
        onClick: function onClick() {
          return setIsOpen(function (isOpen) {
            return !isOpen;
          });
        },
        onMouseDown: handleButtonMouseDown,
        children: /*#__PURE__*/jsxRuntime.jsx(Typography, {
          "data-testid": "neeto-molecules-calendar-view-date-picker-button-label",
          style: "h5",
          children: selectedRangeStr
        })
      }), /*#__PURE__*/jsxRuntime.jsx(DatePicker, _objectSpread$1({
        className: "invisible w-0 px-0",
        defaultValue: selectedDate,
        disabledDate: getDisabledDates,
        open: isOpen,
        placement: "topRight",
        ref: datePickerRef,
        value: selectedDate,
        onChange: setSelectedDate,
        onOpenChange: setIsOpen
      }, _objectSpread$1({
        picker: picker
      }, otherProps))), /*#__PURE__*/jsxRuntime.jsx(Button, {
        className: "ms-1",
        "data-testid": "neeto-molecules-calendar-view-next-button",
        disabled: isDateGreaterThanEnd,
        icon: function icon() {
          return /*#__PURE__*/jsxRuntime.jsx(Right, {
            className: "rtl:scale-x-[-1]",
            size: 20
          });
        },
        style: "text",
        onClick: onNext
      })]
    })]
  });
};

var Header = function Header(_ref) {
  var calendarRef = _ref.calendarRef,
    selectedView = _ref.selectedView,
    setSelectedView = _ref.setSelectedView,
    setSelectedDate = _ref.setSelectedDate,
    selectedDate = _ref.selectedDate,
    calendarViewOptions = _ref.calendarViewOptions,
    validDates = _ref.validDates;
  var Menu = Dropdown.Menu,
    MenuItem = Dropdown.MenuItem;
  var handleViewSelection = function handleViewSelection(option) {
    setSelectedView(option);
    calendarRef.current.calendar.changeView(option.fullCalendarView);
  };
  var navigateToSelectedDate = function navigateToSelectedDate() {
    var _calendarRef$current;
    return calendarRef === null || calendarRef === void 0 || (_calendarRef$current = calendarRef.current) === null || _calendarRef$current === void 0 || (_calendarRef$current = _calendarRef$current.calendar) === null || _calendarRef$current === void 0 ? void 0 : _calendarRef$current.gotoDate(selectedDate.format("YYYY-MM-DD"));
  };
  React.useEffect(function () {
    setTimeout(navigateToSelectedDate);
  }, [selectedDate]);
  return /*#__PURE__*/jsxRuntime.jsxs("div", {
    className: "flex gap-x-4",
    children: [/*#__PURE__*/jsxRuntime.jsx(CustomDatePicker, {
      selectedDate: selectedDate,
      setSelectedDate: setSelectedDate,
      validDates: validDates,
      getPopupContainer: ramda.prop("parentNode"),
      picker: selectedView.picker
    }), Object.keys(calendarViewOptions).length > 1 && /*#__PURE__*/jsxRuntime.jsx(Dropdown, {
      buttonProps: {
        "data-testid": "calendar-view-dropdown"
      },
      buttonStyle: "secondary",
      label: neetoCist.capitalize(selectedView.label),
      children: /*#__PURE__*/jsxRuntime.jsx(Menu, {
        children: ramda.values(calendarViewOptions).map(function (option, idx) {
          return /*#__PURE__*/jsxRuntime.jsx(MenuItem.Button, {
            isActive: selectedView === option,
            onClick: function onClick() {
              return handleViewSelection(option);
            },
            children: neetoCist.capitalize(option.label)
          }, idx);
        })
      })
    })]
  });
};

var _excluded = ["viewOptions", "events", "handleDateClick", "handleEventClick", "eventClassNames", "dayCellClassNames", "validDates", "onDateChange", "dayMaxEvents", "eventMaxStack", "hideHeader"];
function ownKeys(e, r) { var t = Object.keys(e); if (Object.getOwnPropertySymbols) { var o = Object.getOwnPropertySymbols(e); r && (o = o.filter(function (r) { return Object.getOwnPropertyDescriptor(e, r).enumerable; })), t.push.apply(t, o); } return t; }
function _objectSpread(e) { for (var r = 1; r < arguments.length; r++) { var t = null != arguments[r] ? arguments[r] : {}; r % 2 ? ownKeys(Object(t), true).forEach(function (r) { _defineProperty(e, r, t[r]); }) : Object.getOwnPropertyDescriptors ? Object.defineProperties(e, Object.getOwnPropertyDescriptors(t)) : ownKeys(Object(t)).forEach(function (r) { Object.defineProperty(e, r, Object.getOwnPropertyDescriptor(t, r)); }); } return e; }
var direction = i18next.dir() || "ltr";
var CalendarView = /*#__PURE__*/React.forwardRef(function (_ref, ref) {
  var _ref$viewOptions = _ref.viewOptions,
    viewOptions = _ref$viewOptions === void 0 ? VIEW_OPTIONS : _ref$viewOptions,
    _ref$events = _ref.events,
    events = _ref$events === void 0 ? [] : _ref$events,
    _ref$handleDateClick = _ref.handleDateClick,
    handleDateClick = _ref$handleDateClick === void 0 ? neetoCist.noop : _ref$handleDateClick,
    _ref$handleEventClick = _ref.handleEventClick,
    handleEventClick = _ref$handleEventClick === void 0 ? neetoCist.noop : _ref$handleEventClick,
    _ref$eventClassNames = _ref.eventClassNames,
    eventClassNames = _ref$eventClassNames === void 0 ? "" : _ref$eventClassNames,
    _ref$dayCellClassName = _ref.dayCellClassNames,
    dayCellClassNames = _ref$dayCellClassName === void 0 ? "" : _ref$dayCellClassName,
    _ref$validDates = _ref.validDates,
    validDates = _ref$validDates === void 0 ? {
      start: null,
      end: null
    } : _ref$validDates,
    _ref$onDateChange = _ref.onDateChange,
    onDateChange = _ref$onDateChange === void 0 ? neetoCist.noop : _ref$onDateChange,
    dayMaxEvents = _ref.dayMaxEvents,
    eventMaxStack = _ref.eventMaxStack,
    _ref$hideHeader = _ref.hideHeader,
    hideHeader = _ref$hideHeader === void 0 ? false : _ref$hideHeader,
    otherProps = _objectWithoutProperties(_ref, _excluded);
  var calendarViewOptions = viewOptions || VIEW_OPTIONS;
  var defaultView = Object.values(calendarViewOptions).find(ramda.prop("default")) || calendarViewOptions[Object.keys(calendarViewOptions)[0]];
  var _useState = React.useState(defaultView),
    _useState2 = _slicedToArray(_useState, 2),
    selectedView = _useState2[0],
    setSelectedView = _useState2[1];
  var _useState3 = React.useState(utils.dayjs()),
    _useState4 = _slicedToArray(_useState3, 2),
    selectedDate = _useState4[0],
    setSelectedDate = _useState4[1];
  var _useTranslation = reactI18next.useTranslation(),
    t = _useTranslation.t;
  var handleDateChange = function handleDateChange(date) {
    setSelectedDate(function (prevDate) {
      var newDate = typeof date === "function" ? date(prevDate) : date;
      onDateChange(newDate);
      return newDate;
    });
  };
  var calendarWrapperRef = React.useRef(null);
  var calendarRef = React.useRef();
  React.useEffect(function () {
    var _calendarRef$current, _calendarRef$current$;
    var calendarApi = (_calendarRef$current = calendarRef.current) === null || _calendarRef$current === void 0 || (_calendarRef$current$ = _calendarRef$current.getApi) === null || _calendarRef$current$ === void 0 ? void 0 : _calendarRef$current$.call(_calendarRef$current);
    var wrapperElement = calendarWrapperRef.current;
    if (!calendarApi || !wrapperElement) return undefined;
    var handleResize = function handleResize() {
      calendarApi.updateSize();
    };
    var observer = new ResizeObserver(handleResize);
    observer.observe(wrapperElement);
    return function () {
      observer.disconnect();
    };
  }, []);
  return /*#__PURE__*/jsxRuntime.jsxs("div", {
    className: "flex-col",
    "data-testid": "calendar-view",
    ref: calendarWrapperRef,
    children: [!hideHeader && /*#__PURE__*/jsxRuntime.jsx(SubHeader, {
      leftActionBlock: /*#__PURE__*/jsxRuntime.jsx(Typography, {
        style: "h2",
        children: selectedDate.format("MMMM, YYYY")
      }),
      rightActionBlock: /*#__PURE__*/jsxRuntime.jsx(Header, _defineProperty({
        calendarRef: calendarRef,
        calendarViewOptions: calendarViewOptions,
        selectedDate: selectedDate,
        selectedView: selectedView,
        setSelectedDate: setSelectedDate,
        setSelectedView: setSelectedView,
        validDates: validDates
      }, "setSelectedDate", handleDateChange))
    }), /*#__PURE__*/jsxRuntime.jsx(FullCalendar, _objectSpread({
      expandRows: true,
      allDayText: t("neetoMolecules.calendarView.allDay"),
      dateClick: handleDateClick,
      dayHeaderClassNames: "p-2",
      displayEventTime: false,
      eventClick: handleEventClick,
      headerToolbar: false,
      height: "auto",
      initialView: selectedView.fullCalendarView,
      plugins: [dayGridPlugin, timeGridPlugin, interactionPlugin],
      ref: mergeRefs(ref, calendarRef)
    }, _objectSpread({
      dayCellClassNames: dayCellClassNames,
      dayMaxEvents: dayMaxEvents,
      direction: direction,
      eventClassNames: eventClassNames,
      eventMaxStack: eventMaxStack,
      events: events
    }, otherProps)))]
  });
});
CalendarView.displayName = "CalendarView";

module.exports = CalendarView;
//# sourceMappingURL=CalendarView.js.map
