'use strict';

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

var React = require('react');
var formik = require('formik');
var neetoCist = require('@bigbinary/neeto-cist');
var general = require('@bigbinary/neeto-commons-frontend/utils/general');
var Typography = require('@bigbinary/neetoui/Typography');
var reactI18next = require('react-i18next');
var _slicedToArray = require('@babel/runtime/helpers/slicedToArray');
var _toConsumableArray = require('@babel/runtime/helpers/toConsumableArray');
var neetoTimeZones = require('@bigbinary/neeto-time-zones');
var i18next = require('i18next');
var utils = require('@bigbinary/neeto-commons-frontend/utils');
var datetime = require('@bigbinary/neeto-commons-frontend/utils/datetime');
var ramda = require('ramda');
var yup = require('yup');
var _classCallCheck = require('@babel/runtime/helpers/classCallCheck');
var _createClass = require('@babel/runtime/helpers/createClass');
var _defineProperty = require('@babel/runtime/helpers/defineProperty');
var jsxRuntime = require('react/jsx-runtime');
var classnames = require('classnames');
var Copy = require('@bigbinary/neeto-icons/Copy');
var Dropdown = require('@bigbinary/neetoui/Dropdown');
var Button = require('@bigbinary/neetoui/Button');
var Label = require('@bigbinary/neetoui/Label');
var Checkbox = require('@bigbinary/neetoui/Checkbox');
var Switch = require('@bigbinary/neetoui/formik/Switch');
var _typeof = require('@babel/runtime/helpers/typeof');
var Plus = require('@bigbinary/neeto-icons/Plus');
var Delete = require('@bigbinary/neeto-icons/Delete');
var Select = require('@bigbinary/neetoui/formik/Select');
var Profile = require('@bigbinary/neeto-team-members-frontend/Profile');
var Tooltip = require('@bigbinary/neetoui/Tooltip');
var MoreDropdown = require('./MoreDropdown.js');
var injectCss = require('./inject-css-B6qYtOJe.js');
require('@babel/runtime/helpers/objectWithoutProperties');
require('@bigbinary/neeto-icons/MenuHorizontal');
require('@bigbinary/neeto-icons/MenuVertical');
require('@bigbinary/neeto-commons-frontend/react-utils');

function _interopNamespaceDefault(e) {
  var n = Object.create(null);
  if (e) {
    Object.keys(e).forEach(function (k) {
      if (k !== 'default') {
        var d = Object.getOwnPropertyDescriptor(e, k);
        Object.defineProperty(n, k, d.get ? d : {
          enumerable: true,
          get: function () { return e[k]; }
        });
      }
    });
  }
  n.default = e;
  return Object.freeze(n);
}

var yup__namespace = /*#__PURE__*/_interopNamespaceDefault(yup);

var DAYS = ["sunday", "monday", "tuesday", "wednesday", "thursday", "friday", "saturday"];
var DEFAULT_SLOT_INTERVAL = 30;

// To avoid prop drilling `allowAddPeriod` to `ScheduleRow` component
// eslint-disable-next-line @bigbinary/neeto/use-zustand-for-global-state-management
var ScheduleContext = /*#__PURE__*/React.createContext({
  allowAddPeriod: true,
  firstDay: 0
});

var INTERVALS = ["year", "quarter", "month", "week", "day", "hour", "minute", "second"];

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 REMOVE_SELECT_DOWN_ARROW = {
  DropdownIndicator: function DropdownIndicator() {
    return null;
  },
  IndicatorSeparator: function IndicatorSeparator() {
    return null;
  }
};
var BLUR_TEXT_WHEN_SELECT_MENU_IS_OPEN = {
  singleValue: function singleValue(base, state) {
    return _objectSpread(_objectSpread({}, base), {}, {
      color: state.selectProps.menuIsOpen ? "#c2c8cc" : base.color
    });
  }
};
var SLOT_TIME_FORMAT = "hh:mm A";

// eslint-disable-next-line @bigbinary/neeto/use-standard-date-time-formats
var END_OF_DAY = utils.dayjs().endOf("day").format(SLOT_TIME_FORMAT);

var DayjsRange = /*#__PURE__*/function () {
  function DayjsRange(startDate, endDate) {
    _classCallCheck(this, DayjsRange);
    var _ref = startDate > endDate ? {
        s: endDate,
        e: startDate
      } : {
        s: startDate,
        e: endDate
      },
      s = _ref.s,
      e = _ref.e;
    this.startDate = s;
    this.endDate = e;
  }
  return _createClass(DayjsRange, [{
    key: "isValidRange",
    value: function isValidRange() {
      return this.startDate.isValid() && this.endDate.isValid();
    }
  }, {
    key: "isOverlap",
    value: function isOverlap(other) {
      if (!(other instanceof DayjsRange) || !other.isValidRange()) {
        return false;
      }
      return this.startDate < other.endDate && this.endDate > other.startDate;
    }
  }, {
    key: "toArrayOfTimeIntervals",
    value: function toArrayOfTimeIntervals() {
      var interval = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 15;
      var startTime = this.startDate;
      var endTime = this.endDate.add(1, "days");
      var allTimes = [];
      while (startTime < endTime) {
        allTimes.push(startTime.format(SLOT_TIME_FORMAT));
        startTime = startTime.add(interval, "minutes");
      }
      return allTimes;
    }
  }]);
}();
function extendDayjs(dayjs) {
  dayjs.range = function range(start, end) {
    var dayjsObject = this;
    if (typeof start === "string" && INTERVALS.includes(start)) {
      return new DayjsRange(dayjs(dayjsObject).startOf(start), dayjs(dayjsObject).endOf(start));
    }
    return new DayjsRange(start, end);
  };
  dayjs.range.constructor = DayjsRange;

  // Returns timeIntervals in 12 hour clock format for the whole day with both AM or PM suffixed
  dayjs.timeIntervalsForDay = function (interval) {
    var _ref2 = [dayjs().startOf("day"), dayjs().startOf("day")],
      startOfDay = _ref2[0],
      endOfDay = _ref2[1];
    return dayjs.range(startOfDay, endOfDay).toArrayOfTimeIntervals(interval);
  };
  return dayjs;
}

// Add range and overlap functions to dayjs
var dayjsExtended = extendDayjs(utils.dayjs);

function _createForOfIteratorHelper(r, e) { var t = "undefined" != typeof Symbol && r[Symbol.iterator] || r["@@iterator"]; if (!t) { if (Array.isArray(r) || (t = _unsupportedIterableToArray(r)) || e) { t && (r = t); var _n = 0, F = function F() {}; return { s: F, n: function n() { return _n >= r.length ? { done: true } : { done: false, value: r[_n++] }; }, e: function e(r) { throw r; }, f: F }; } throw new TypeError("Invalid attempt to iterate non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); } var o, a = true, u = false; return { s: function s() { t = t.call(r); }, n: function n() { var r = t.next(); return a = r.done, r; }, e: function e(r) { u = true, o = r; }, f: function f() { try { a || null == t["return"] || t["return"](); } finally { if (u) throw o; } } }; }
function _unsupportedIterableToArray(r, a) { if (r) { if ("string" == typeof r) return _arrayLikeToArray(r, a); var t = {}.toString.call(r).slice(8, -1); return "Object" === t && r.constructor && (t = r.constructor.name), "Map" === t || "Set" === t ? Array.from(r) : "Arguments" === t || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(t) ? _arrayLikeToArray(r, a) : void 0; } }
function _arrayLikeToArray(r, a) { (null == a || a > r.length) && (a = r.length); for (var e = 0, n = Array(a); e < a; e++) n[e] = r[e]; return n; }
yup__namespace.addMethod(yup__namespace.array, "ensureSlotsCantOverlap", function () {
  return this.test("ensureSlotsCantOverlap", function (periods) {
    var _checkForOverlapBetwe = checkForOverlapBetweenPeriods(periods),
      isOverlapping = _checkForOverlapBetwe.exists,
      range1 = _checkForOverlapBetwe.range1,
      range2 = _checkForOverlapBetwe.range2;
    if (!isOverlapping) return true;
    var _findIndicesOfOverlap = findIndicesOfOverlappingRangesInPeriods({
        range1: range1,
        range2: range2,
        periods: periods
      }),
      firstIndex = _findIndicesOfOverlap.firstIndex,
      secondIndex = _findIndicesOfOverlap.secondIndex;
    var firstError = this.createError({
      path: "".concat(this.path, "[").concat(firstIndex, "]"),
      message: i18next.t("neetoMolecules.schedule.errors.period.overlap", {
        start: datetime.timeFormat.time(range2.startDate),
        end: datetime.timeFormat.time(range2.endDate)
      })
    });
    var secondError = this.createError({
      path: "".concat(this.path, "[").concat(secondIndex, "]"),
      message: i18next.t("neetoMolecules.schedule.errors.period.overlap", {
        start: datetime.timeFormat.time(range1.startDate),
        end: datetime.timeFormat.time(range1.endDate)
      })
    });
    return new yup__namespace.ValidationError([firstError, secondError]);
  });
});
var isFromAndToSame = function isFromAndToSame(startTime, endTime) {
  if (!startTime || !endTime) return true;
  return utils.dayjs(startTime, SLOT_TIME_FORMAT).isSame(utils.dayjs(endTime, SLOT_TIME_FORMAT));
};
var sortDays = function sortDays(chosenIndex) {
  if (chosenIndex < 0 || chosenIndex >= 7) return DAYS;
  return [].concat(_toConsumableArray(DAYS.slice(chosenIndex)), _toConsumableArray(DAYS.slice(0, chosenIndex)));
};
var wdayValidation = yup__namespace.object().shape({
  periods: yup__namespace.array().of(yup__namespace.object().shape({
    startTime: yup__namespace.string().required(i18next.t("neetoMolecules.schedule.errors.period.startTime")),
    endTime: yup__namespace.string().required(i18next.t("neetoMolecules.schedule.errors.period.endTime")).test("ensureToTimeNotBehindFromTime", i18next.t("neetoMolecules.schedule.errors.period.isBehind"), function (value) {
      var startTime = this.parent.startTime;
      if (isFromAndToSame(value, startTime)) return true;
      return isTimeBehind(startTime, value);
    })
  }).test("ensureTimeNotSame", i18next.t("neetoMolecules.schedule.errors.period.sameTime"), function (value) {
    var startTime = value.startTime,
      endTime = value.endTime;
    return !isFromAndToSame(startTime, endTime);
  })).ensureSlotsCantOverlap()
});
var getScheduleValidationSchema = function getScheduleValidationSchema() {
  return yup__namespace.object().shape({
    wdays: yup__namespace.object().shape(ramda.fromPairs(ramda.map(function (day) {
      return [day, wdayValidation];
    }, DAYS)))
  });
};
var getUserTimeZone = function getUserTimeZone() {
  var _window$globalProps;
  return (_window$globalProps = window.globalProps) === null || _window$globalProps === void 0 ? void 0 : _window$globalProps.user.timeZone;
};
var getTimeZoneAndTime = function getTimeZoneAndTime() {
  var timeZone = getUserTimeZone();
  var humanReadableTimezone = neetoTimeZones.ianaTimezoneToHumanReadable(timeZone);

  // Requires timezone initialization
  // eslint-disable-next-line @bigbinary/neeto/use-standard-date-time-formats
  return "".concat(humanReadableTimezone, ": ").concat(utils.dayjs().tz(timeZone).format(SLOT_TIME_FORMAT));
};
var isTimeBehind = function isTimeBehind(timeA, timeB) {
  return utils.dayjs(timeA, SLOT_TIME_FORMAT).isBefore(utils.dayjs(timeB, SLOT_TIME_FORMAT));
};
var sortPeriodsByKey = function sortPeriodsByKey(_ref) {
  var periods = _ref.periods,
    key = _ref.key,
    _ref$order = _ref.order,
    order = _ref$order === void 0 ? "desc" : _ref$order;
  return periods.slice().sort(function (periodA, periodB) {
    var isPeriodBehind = isTimeBehind(periodA[key], periodB[key]);
    if (order === "desc") return isPeriodBehind ? 1 : -1;
    return isPeriodBehind ? -1 : 1;
  });
};

/**
 * Check for overlapping between entered periods
 * @typedef {Object} Slots
 * @property {Array<{startTime:string, endTime: string}>} periods - startTime and endTime
 * @param {Slots} periods - changed time periods
 * @return {{exists: boolean, range1: DayjsRange | null, range2:DayjsRange | null }} - overlapped ranges if exists
 */
var checkForOverlapBetweenPeriods = function checkForOverlapBetweenPeriods(periods) {
  var response = {
    exists: false,
    range1: null,
    range2: null
  };
  if (!(periods !== null && periods !== void 0 && periods.length)) return response;
  var slotsSortedByStartTime = sortPeriodsByKey({
    periods: periods,
    key: "startTime"
  });
  var _iterator = _createForOfIteratorHelper(slotsSortedByStartTime.slice(0, -1).entries()),
    _step;
  try {
    for (_iterator.s(); !(_step = _iterator.n()).done;) {
      var _step$value = _slicedToArray(_step.value, 2),
        index = _step$value[0],
        value = _step$value[1];
      var seg1 = value;
      var seg2 = slotsSortedByStartTime[index + 1];
      var range1 = dayjsExtended.range(dayjsExtended(seg1.startTime, SLOT_TIME_FORMAT), dayjsExtended(seg1.endTime, SLOT_TIME_FORMAT));
      var range2 = dayjsExtended.range(dayjsExtended(seg2.startTime, SLOT_TIME_FORMAT), dayjsExtended(seg2.endTime, SLOT_TIME_FORMAT));
      if (range1.isOverlap(range2)) {
        response = {
          exists: true,
          range1: range1,
          range2: range2
        };
        break;
      }
    }
  } catch (err) {
    _iterator.e(err);
  } finally {
    _iterator.f();
  }
  return response;
};
var findIndicesOfOverlappingRangesInPeriods = function findIndicesOfOverlappingRangesInPeriods(_ref2) {
  var range1 = _ref2.range1,
    range2 = _ref2.range2,
    periods = _ref2.periods;
  var firstIndex = neetoCist.findIndexBy({
    startTime: range1.startDate.format(SLOT_TIME_FORMAT)
  }, periods);
  var secondIndex = periods.findIndex(function (slot, index) {
    return index > firstIndex && slot.startTime === range2.startDate.format(SLOT_TIME_FORMAT);
  });
  return {
    firstIndex: firstIndex,
    secondIndex: secondIndex
  };
};
var handleCopy = function handleCopy(_ref3) {
  var _values$wdays$day$per;
  var values = _ref3.values,
    day = _ref3.day,
    setFieldValue = _ref3.setFieldValue,
    wdaysToCopy = _ref3.wdaysToCopy;
  var newPeriods = (_values$wdays$day$per = values.wdays[day].periods) === null || _values$wdays$day$per === void 0 ? void 0 : _values$wdays$day$per.map(ramda.pick(["startTime", "endTime"]));
  if (neetoCist.isNotPresent(newPeriods)) return;
  wdaysToCopy.forEach(function (wday) {
    return setFieldValue("wdays.".concat(wday), {
      available: true,
      periods: newPeriods.map(ramda.assoc("wday", wday))
    });
  });
};
var buildFormValuesArray = function buildFormValuesArray(_ref4) {
  var firstDay = _ref4.firstDay,
    periods = _ref4.periods;
  return sortDays(firstDay).map(function (wday) {
    var _periods$wday;
    return {
      periods: sortPeriodsByKey({
        periods: periods[wday],
        key: "startTime",
        order: "asc"
      }),
      available: !!((_periods$wday = periods[wday]) !== null && _periods$wday !== void 0 && _periods$wday.length),
      wday: wday
    };
  });
};
var buildFormValuesObject = function buildFormValuesObject(_ref5) {
  var periods = _ref5.periods;
  var formValues = {};
  DAYS.forEach(function (wday) {
    var _periods$wday2;
    formValues[wday] = {
      periods: sortPeriodsByKey({
        periods: periods[wday],
        key: "startTime",
        order: "asc"
      }),
      available: !!((_periods$wday2 = periods[wday]) !== null && _periods$wday2 !== void 0 && _periods$wday2.length),
      wday: wday
    };
  });
  return formValues;
};
var processFormValues = function processFormValues(values, firstDay) {
  return {
    wdays: buildFormValuesArray({
      firstDay: firstDay,
      periods: ramda.map(ramda.prop("periods"), values.wdays)
    })
  };
};

var DisplayAvailability = function DisplayAvailability(_ref) {
  var periods = _ref.periods;
  var _useTranslation = reactI18next.useTranslation(),
    t = _useTranslation.t;
  var _useContext = React.useContext(ScheduleContext),
    firstDay = _useContext.firstDay;
  return /*#__PURE__*/jsxRuntime.jsx("div", {
    className: "flex w-full flex-col gap-y-3",
    children: sortDays(firstDay).map(function (day) {
      var _sortPeriodsByKey;
      return /*#__PURE__*/jsxRuntime.jsxs("div", {
        className: "neeto-ui-rounded-md neeto-ui-border-gray-300 neeto-ui-bg-white flex w-full flex-wrap items-center justify-center gap-2 border px-6 py-4 sm:items-start sm:justify-start",
        "data-cy": "day-cards-".concat(day),
        children: [/*#__PURE__*/jsxRuntime.jsx(Typography, {
          className: "mt-0.5 w-24 text-center sm:w-1/4 sm:text-start",
          "data-cy": general.joinHyphenCase(day, "day-text"),
          style: "h5",
          weight: "semibold",
          children: t("neetoMolecules.schedule.days.".concat(day))
        }), /*#__PURE__*/jsxRuntime.jsx("div", {
          className: "flex flex-grow flex-col items-center gap-y-4 sm:w-1/2",
          children: neetoCist.isPresent(periods[day]) ? (_sortPeriodsByKey = sortPeriodsByKey({
            periods: periods[day],
            key: "startTime",
            order: "asc"
          })) === null || _sortPeriodsByKey === void 0 ? void 0 : _sortPeriodsByKey.map(function (period) {
            return /*#__PURE__*/jsxRuntime.jsxs("div", {
              className: "flex items-center gap-x-4",
              children: [/*#__PURE__*/jsxRuntime.jsx(Typography, {
                className: "w-20 text-end",
                lineHeight: "relaxed",
                style: "h5",
                weight: "semibold",
                "data-cy": general.joinHyphenCase(day, period.startTime, "start-time-text"),
                children: period.startTime
              }), /*#__PURE__*/jsxRuntime.jsx(Typography, {
                className: "neeto-ui-text-gray-600",
                component: "span",
                children: "-"
              }), /*#__PURE__*/jsxRuntime.jsx(Typography, {
                className: "w-20 text-start",
                lineHeight: "relaxed",
                style: "h5",
                weight: "semibold",
                "data-cy": general.joinHyphenCase(day, period.endTime, "start-time-text"),
                children: period.endTime
              })]
            }, period.id);
          }) : /*#__PURE__*/jsxRuntime.jsx(Typography, {
            className: "mx-8 flex-grow text-center",
            "data-cy": general.joinHyphenCase(day, "unavailable-time-text"),
            lineHeight: "relaxed",
            style: "h5",
            children: t("neetoMolecules.schedule.unavailable")
          })
        })]
      }, day);
    })
  });
};

var buildSlotIntervals = function buildSlotIntervals(_ref) {
  var interval = _ref.interval,
    bookedSlots = _ref.bookedSlots;
  var allIntervalsForADay = dayjsExtended.timeIntervalsForDay(interval);
  allIntervalsForADay.push(END_OF_DAY);
  return function (slotType) {
    var selectedValue = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : null;
    var uniqBookedSlots = ramda.uniq(ramda.pluck(slotType, bookedSlots));
    var slotsAvailableForBooking = ramda.difference(allIntervalsForADay, uniqBookedSlots);
    var slots = slotsAvailableForBooking.map(neetoCist.toLabelAndValue);
    if (!selectedValue) return slots;
    return sortSlots([neetoCist.toLabelAndValue(selectedValue)].concat(_toConsumableArray(slots)));
  };
};
var sortSlots = function sortSlots(slots) {
  return slots.sort(function (a, b) {
    return isTimeBehind(a["value"], b["value"]) ? -1 : 1;
  });
};
var slotsSelectComponentDefaultValue = function slotsSelectComponentDefaultValue(slot) {
  return slot ? neetoCist.toLabelAndValue(slot) : "";
};
var padZeroes = function padZeroes(str) {
  return str.length % 2 === 0 ? str : "0".concat(str);
};
var filterSlots = function filterSlots(option, searchTerm) {
  if (neetoCist.isNotPresent(searchTerm) || option.data.__isNew__) return true;
  var doesNumberMatches = option.value.replace(":", "").startsWith(padZeroes(searchTerm.replaceAll(/\D+/gi, "")));
  var doesAmPmMatches = option.value.includes(searchTerm.toUpperCase().replaceAll(/[^a-z]/gi, ""));
  return doesNumberMatches && doesAmPmMatches;
};
var formatCreateLabel = ramda.identity;
var isValidTimeSlotOption = function isValidTimeSlotOption(value) {
  // Allow HH:MM AM/PM, H:MM AM/PM, H:MM am/pm, or HH:MM (24h)
  // Accepts 1 or 2 digit hour (1-12) with AM/PM OR 00-23:00-59 for 24h, AM/PM (any case) optional, optional leading zero
  // eslint-disable-next-line prettier/prettier
  var timeRegex = /^(((0?[1-9]|1[0-2]):[0-5]\d ?[AaPp][Mm])|([01]?\d|2[0-3]):[0-5]\d)$/;
  return timeRegex.test(value);
};
var formatTimeSlotOption = function formatTimeSlotOption(v) {
  var value = (v || "").toUpperCase();
  if (neetoCist.isNotEmpty(value)) {
    // If value is in 24h format and missing AM/PM, convert to 12h with AM/PM
    var time24hMatch = value.match(/^([01]?\d|2[0-3]):([0-5]\d)$/);
    if (time24hMatch) {
      var _time24hMatch = _slicedToArray(time24hMatch, 3),
        hours = _time24hMatch[1],
        minutes = _time24hMatch[2];
      var hoursInt = parseInt(hours, 10);
      var suffix = hoursInt >= 12 ? "PM" : "AM";
      var hour12 = hoursInt % 12 || 12;
      value = "".concat(hour12.toString().padStart(2, "0"), ":").concat(minutes, " ").concat(suffix);
    } else if (value[1] === ":") {
      // Pad hour with 0 if single digit (legacy logic)
      value = "0".concat(value);
    }
  }
  return value;
};
var roundToNearestHour = function roundToNearestHour(time) {
  var minutes = time.minute();
  if (minutes === 59) return time.startOf("hour").add(1, "hour");
  return time.add(1, "hour");
};
var generateNewPeriod = function generateNewPeriod(periods, wday) {
  var lastEndTime = periods[periods.length - 1].endTime;
  var newStartTime = roundToNearestHour(dayjsExtended(lastEndTime, SLOT_TIME_FORMAT));
  var newEndTime = dayjsExtended(newStartTime, SLOT_TIME_FORMAT).add(1, "hour");
  return {
    startTime: dayjsExtended(newStartTime).format(SLOT_TIME_FORMAT),
    endTime: dayjsExtended(newEndTime).format(SLOT_TIME_FORMAT),
    wday: wday
  };
};
var addDefaultPeriod = function addDefaultPeriod(wday) {
  return {
    wday: wday,
    startTime: dayjsExtended().hour(9).minute(0).format(SLOT_TIME_FORMAT),
    endTime: dayjsExtended().hour(17).minute(0).format(SLOT_TIME_FORMAT)
  };
};

var ScheduleRow = function ScheduleRow(_ref) {
  var day = _ref.day;
  var _useFormikContext = formik.useFormikContext(),
    values = _useFormikContext.values,
    setFieldValue = _useFormikContext.setFieldValue;
  var bookedSlots = values.wdays[day].periods;
  var _useContext = React.useContext(ScheduleContext),
    allowAddPeriod = _useContext.allowAddPeriod,
    slotInterval = _useContext.slotInterval;
  var _useTranslation = reactI18next.useTranslation(),
    t = _useTranslation.t;
  var sortSlotsInterval = React.useMemo(function () {
    return buildSlotIntervals({
      interval: slotInterval,
      bookedSlots: bookedSlots
    });
  }, [slotInterval, bookedSlots]);
  var handleChange = function handleChange(index, field, e) {
    var value = formatTimeSlotOption(e === null || e === void 0 ? void 0 : e.value);
    setFieldValue("wdays.".concat(day, ".periods[").concat(index, "].").concat(field), value);
  };
  var handleAddRow = function handleAddRow(arrayHelpers) {
    if (neetoCist.isNotPresent(values.wdays[day].periods)) {
      arrayHelpers.push(addDefaultPeriod(day));
    } else {
      arrayHelpers.push(generateNewPeriod(values.wdays[day].periods, day));
    }
    setFieldValue("wdays.".concat(day, ".available"), true);
  };
  var handleDeleteRow = function handleDeleteRow(arrayHelpers, index) {
    var isLastRowDeleted = values.wdays[day].periods.length === 1;
    arrayHelpers.remove(index);
    setFieldValue("wdays.".concat(day, ".available"), !isLastRowDeleted);
  };
  return /*#__PURE__*/jsxRuntime.jsx(formik.FieldArray, {
    name: "wdays.".concat(day, ".periods"),
    render: function render(arrayHelpers) {
      var _values$wdays$day, _values$wdays$day$per;
      return /*#__PURE__*/jsxRuntime.jsxs(jsxRuntime.Fragment, {
        children: [neetoCist.isPresent((_values$wdays$day = values.wdays[day]) === null || _values$wdays$day === void 0 ? void 0 : _values$wdays$day.periods) && /*#__PURE__*/jsxRuntime.jsx("div", {
          className: "flex w-full flex-col gap-y-2",
          children: (_values$wdays$day$per = values.wdays[day].periods) === null || _values$wdays$day$per === void 0 ? void 0 : _values$wdays$day$per.map(function (period, index) {
            return /*#__PURE__*/jsxRuntime.jsxs("div", {
              className: "flex w-full flex-col @xl:mx-auto @xl:w-80",
              children: [/*#__PURE__*/jsxRuntime.jsxs("div", {
                className: "flex items-start gap-2 @xl:gap-3",
                "data-cy": "schedule-row",
                children: [/*#__PURE__*/jsxRuntime.jsx(Select, {
                  formatCreateLabel: formatCreateLabel,
                  isClearable: true,
                  isCreateable: true,
                  isSearchable: true,
                  className: "w-full",
                  components: REMOVE_SELECT_DOWN_ARROW,
                  filterOption: filterSlots,
                  isValidNewOption: isValidTimeSlotOption,
                  name: "wdays.".concat(day, ".periods[").concat(index, "].startTime"),
                  placeholder: t("neetoMolecules.schedule.startTime"),
                  strategy: "fixed",
                  styles: BLUR_TEXT_WHEN_SELECT_MENU_IS_OPEN,
                  options: sortSlotsInterval("startTime", period === null || period === void 0 ? void 0 : period.startTime),
                  value: slotsSelectComponentDefaultValue(period === null || period === void 0 ? void 0 : period.startTime),
                  onChange: function onChange(e) {
                    return handleChange(index, "startTime", e);
                  }
                }), /*#__PURE__*/jsxRuntime.jsx(Select, {
                  formatCreateLabel: formatCreateLabel,
                  isClearable: true,
                  isCreateable: true,
                  isSearchable: true,
                  className: "w-full",
                  components: REMOVE_SELECT_DOWN_ARROW,
                  filterOption: filterSlots,
                  isValidNewOption: isValidTimeSlotOption,
                  name: "wdays.".concat(day, ".periods[").concat(index, "].endTime"),
                  options: sortSlotsInterval("endTime", period === null || period === void 0 ? void 0 : period.endTime),
                  placeholder: t("neetoMolecules.schedule.endTime"),
                  strategy: "fixed",
                  styles: BLUR_TEXT_WHEN_SELECT_MENU_IS_OPEN,
                  value: slotsSelectComponentDefaultValue(period === null || period === void 0 ? void 0 : period.endTime),
                  onChange: function onChange(e) {
                    return handleChange(index, "endTime", e);
                  }
                }), /*#__PURE__*/jsxRuntime.jsx(Button, {
                  className: "flex-shrink-0 self-start",
                  "data-cy": "delete-period-button",
                  "data-testid": "delete-period-button",
                  icon: Delete,
                  style: "text",
                  onClick: function onClick() {
                    return handleDeleteRow(arrayHelpers, index);
                  }
                })]
              }), /*#__PURE__*/jsxRuntime.jsx(formik.ErrorMessage, {
                name: "wdays.".concat(day, ".periods[").concat(index, "]"),
                children: function children(message) {
                  return _typeof(message) !== "object" && /*#__PURE__*/jsxRuntime.jsx("span", {
                    className: "neeto-ui-text-error-500 mt-1 w-11/12 px-2 text-xs",
                    children: message
                  });
                }
              })]
            }, "wdays.".concat(day, ".periods[").concat(index, "]"));
          })
        }), values.wdays[day].available && allowAddPeriod && /*#__PURE__*/jsxRuntime.jsx(Button, {
          className: "absolute end-14 top-3 ms-auto flex-shrink-0 @xl:static",
          "data-cy": "add-new-period-button",
          "data-testid": "add-new-period-button",
          icon: Plus,
          style: "secondary",
          tooltipProps: {
            content: t("neetoMolecules.schedule.addNewPeriod"),
            position: "top",
            hideAfter: 5000,
            touch: ["hold", 500]
          },
          onClick: function onClick() {
            return handleAddRow(arrayHelpers);
          }
        })]
      });
    }
  });
};
var ScheduleRow$1 = /*#__PURE__*/React.memo(ScheduleRow);

var Form = function Form(_ref) {
  var _values$wdays$day;
  var day = _ref.day;
  var _useState = React.useState([]),
    _useState2 = _slicedToArray(_useState, 2),
    deletedPeriods = _useState2[0],
    setDeletedPeriods = _useState2[1];
  var _useState3 = React.useState([]),
    _useState4 = _slicedToArray(_useState3, 2),
    wdaysToCopy = _useState4[0],
    setWdaysToCopy = _useState4[1];
  var _useFormikContext = formik.useFormikContext(),
    values = _useFormikContext.values,
    setFieldValue = _useFormikContext.setFieldValue;
  var _useTranslation = reactI18next.useTranslation(),
    t = _useTranslation.t;
  var _useContext = React.useContext(ScheduleContext),
    firstDay = _useContext.firstDay;
  var restoreDeletedPeriods = function restoreDeletedPeriods() {
    setFieldValue("wdays.".concat(day, ".periods"), deletedPeriods);
  };
  var uncheckCheckbox = function uncheckCheckbox() {
    var _values$wdays$day$per;
    setFieldValue("wdays.".concat(day, ".available"), false);
    setFieldValue("wdays.".concat(day, ".periods"), []);
    if ((_values$wdays$day$per = values.wdays[day].periods[0]) !== null && _values$wdays$day$per !== void 0 && _values$wdays$day$per.id) {
      setDeletedPeriods(values.wdays[day].periods.filter(function (item) {
        return item.startTime && item.endTime;
      }).map(ramda.identity));
    }
  };
  var checkCheckbox = function checkCheckbox() {
    var _deletedPeriods$;
    setFieldValue("wdays.".concat(day, ".available"), true);
    if ((_deletedPeriods$ = deletedPeriods[0]) !== null && _deletedPeriods$ !== void 0 && _deletedPeriods$.startTime) {
      restoreDeletedPeriods();
    } else if (neetoCist.isNotPresent(values.wdays[day].periods)) {
      setFieldValue("wdays.".concat(day, ".periods"), [addDefaultPeriod(day)]);
    } else {
      setFieldValue("wdays.".concat(day, ".periods"), [""]);
    }
  };
  var handleCheckbox = function handleCheckbox() {
    if (values.wdays[day].available) {
      uncheckCheckbox();
    } else {
      checkCheckbox();
    }
  };
  var handleCopyChange = function handleCopyChange(e, day) {
    return setWdaysToCopy(e.target.checked ? ramda.append(day) : ramda.without([day]));
  };
  return /*#__PURE__*/jsxRuntime.jsx("div", {
    className: "neeto-ui-rounded-md neeto-ui-border-gray-300 neeto-ui-bg-white relative mb-3 w-full border px-4 @container last:mb-0 md:px-6",
    children: /*#__PURE__*/jsxRuntime.jsxs("div", {
      className: "@xl:flex-no-wrap my-4 flex w-full flex-wrap items-start gap-2 @xl:flex-nowrap @xl:gap-4" // Added `@xl:flex-no-wrap` since neetoCal is using old version of tailwind
      ,
      "data-cy": "working-day-container",
      children: [/*#__PURE__*/jsxRuntime.jsxs("div", {
        className: classnames("flex w-36 flex-shrink-0 items-center justify-start @xl:mt-1", {
          "mb-3 @xl:mb-0": neetoCist.isPresent((_values$wdays$day = values.wdays[day]) === null || _values$wdays$day === void 0 ? void 0 : _values$wdays$day.periods)
        }),
        children: [/*#__PURE__*/jsxRuntime.jsx(Switch, {
          "aria-label": "wdays.".concat(day, ".available"),
          checked: values.wdays[day].available,
          className: "flex-grow-0",
          "data-cy": general.joinHyphenCase(day, "weekly-hours-checkbox"),
          id: "day",
          name: "wdays.".concat(day, ".available"),
          onChange: handleCheckbox
        }), /*#__PURE__*/jsxRuntime.jsx(Typography, {
          component: "span",
          "data-cy": general.joinHyphenCase(day, "day-text"),
          style: "body2",
          weight: values.wdays[day].available ? "semibold" : "normal",
          className: classnames("ms-2 capitalize", {
            "neeto-ui-text-gray-600": !values.wdays[day].available
          }),
          children: t("neetoMolecules.schedule.days.".concat(day))
        })]
      }), /*#__PURE__*/jsxRuntime.jsx(ScheduleRow$1, {
        day: day
      }), values.wdays[day].available && /*#__PURE__*/jsxRuntime.jsxs(Dropdown, {
        closeOnSelect: true,
        buttonStyle: "secondary",
        icon: Copy,
        position: "right-start",
        buttonProps: {
          tooltipProps: {
            content: t("neetoMolecules.schedule.copyScheduleTooltip"),
            position: "top",
            hideAfter: 5000,
            touch: ["hold", 500]
          },
          className: "absolute end-4 top-3 @xl:static flex-shrink-0",
          "data-testid": general.joinHyphenCase(day, "copy-schedule-icon"),
          "data-cy": general.joinHyphenCase(day, "copy-schedule-icon")
        },
        dropdownProps: {
          className: "neeto-ui-dropdown__popup neeto-molecules-schedule__dropdown"
        },
        onClose: function onClose() {
          return setWdaysToCopy([]);
        },
        children: [/*#__PURE__*/jsxRuntime.jsx("li", {
          children: /*#__PURE__*/jsxRuntime.jsx(Typography, {
            style: "h5",
            children: t("neetoMolecules.schedule.copySchedule")
          })
        }), sortDays(firstDay).filter(function (copyDay) {
          return copyDay !== day;
        }).map(function (day) {
          return /*#__PURE__*/jsxRuntime.jsx("li", {
            onClick: function onClick(e) {
              return e.stopPropagation();
            },
            children: /*#__PURE__*/jsxRuntime.jsx(Label, {
              className: "w-full cursor-pointer capitalize",
              children: /*#__PURE__*/jsxRuntime.jsx(Checkbox, {
                checked: wdaysToCopy.includes(day),
                id: day,
                label: t("neetoMolecules.schedule.days.".concat(day)),
                onChange: function onChange(e) {
                  return handleCopyChange(e, day);
                }
              })
            })
          }, day);
        }), /*#__PURE__*/jsxRuntime.jsx("li", {
          children: /*#__PURE__*/jsxRuntime.jsx(Button, {
            "data-cy": "copy-schedule-submit-button",
            disabled: neetoCist.isNotPresent(wdaysToCopy),
            label: t("neetoMolecules.common.actions.submit"),
            size: "small",
            onClick: function onClick() {
              handleCopy({
                values: values,
                day: day,
                setFieldValue: setFieldValue,
                wdaysToCopy: wdaysToCopy
              });
              setWdaysToCopy([]);
            }
          })
        })]
      })]
    })
  });
};
var Form$1 = /*#__PURE__*/React.memo(Form);

var Fields = function Fields(_ref) {
  var handleValuesChanged = _ref.handleValuesChanged,
    scheduleRef = _ref.scheduleRef;
  var _useContext = React.useContext(ScheduleContext),
    firstDay = _useContext.firstDay;
  var formikBag = formik.useFormikContext();
  var values = formikBag.values,
    resetForm = formikBag.resetForm,
    errors = formikBag.errors;
  React.useEffect(function () {
    handleValuesChanged(processFormValues(values, firstDay), formikBag);
  }, [values]);
  React.useImperativeHandle(scheduleRef, function () {
    return {
      resetForm: resetForm,
      errors: errors
    };
  });
  return sortDays(firstDay).map(function (wday) {
    return /*#__PURE__*/jsxRuntime.jsx(Form$1, {
      day: wday
    }, wday);
  });
};

var Header = function Header(_ref) {
  var isCreating = _ref.isCreating,
    isEditable = _ref.isEditable,
    isEditing = _ref.isEditing,
    setIsEditing = _ref.setIsEditing,
    _ref$showTimeZone = _ref.showTimeZone,
    showTimeZone = _ref$showTimeZone === void 0 ? true : _ref$showTimeZone;
  var _useFormikContext = formik.useFormikContext(),
    dirty = _useFormikContext.dirty,
    resetForm = _useFormikContext.resetForm,
    submitForm = _useFormikContext.submitForm,
    isSubmitting = _useFormikContext.isSubmitting;
  var _useTranslation = reactI18next.useTranslation(),
    t = _useTranslation.t;
  var _useState = React.useState(getTimeZoneAndTime()),
    _useState2 = _slicedToArray(_useState, 2),
    timeZoneAndTime = _useState2[0],
    setTimeZoneAndTime = _useState2[1];
  var _Profile$usePaneState = Profile.usePaneState(),
    _Profile$usePaneState2 = _slicedToArray(_Profile$usePaneState, 2);
    _Profile$usePaneState2[0];
    var setIsProfilePaneOpen = _Profile$usePaneState2[1];
  var handleReset = function handleReset() {
    if (dirty) resetForm();else setIsEditing(false);
  };
  React.useEffect(function () {
    var time = setInterval(function () {
      setTimeZoneAndTime(getTimeZoneAndTime());
    }, 30000);
    return function () {
      return clearInterval(time);
    };
  }, []);
  return /*#__PURE__*/jsxRuntime.jsxs("div", {
    className: "mb-6 flex flex-wrap justify-between gap-2",
    children: [showTimeZone && /*#__PURE__*/jsxRuntime.jsxs("div", {
      className: "flex items-center gap-3",
      "data-testid": "schedule-timezone-header",
      children: [/*#__PURE__*/jsxRuntime.jsx(Tooltip, {
        content: t("neetoMolecules.schedule.timezoneTooltip"),
        position: "bottom",
        touch: ["hold", 500],
        children: /*#__PURE__*/jsxRuntime.jsx(Typography, {
          component: "h4",
          "data-cy": "timezone-text",
          style: "h5",
          weight: "medium",
          children: timeZoneAndTime
        })
      }), isEditable && /*#__PURE__*/jsxRuntime.jsx(MoreDropdown, {
        dropdownButtonProps: {
          "data-testid": "nui-more-dropdown"
        },
        menuItems: [{
          onClick: function onClick() {
            return setIsProfilePaneOpen(true);
          },
          label: t("neetoMolecules.common.actions.changeTimezone"),
          target: "_blank",
          key: "change-timezone-option",
          "data-testid": "change-timezone-option",
          "data-cy": "change-timezone-option"
        }]
      })]
    }), isEditing ? /*#__PURE__*/jsxRuntime.jsxs("div", {
      className: "flex items-center gap-2",
      children: [/*#__PURE__*/jsxRuntime.jsx(Button, {
        "data-cy": "reset-button",
        style: "secondary",
        label: !dirty ? t("neetoMolecules.common.actions.cancel") : t("neetoMolecules.common.actions.reset"),
        onClick: handleReset
      }), /*#__PURE__*/jsxRuntime.jsx(Button, {
        "data-cy": "weekly-hours-save-changes-button",
        disabled: !dirty && !isCreating || isSubmitting,
        label: t("neetoMolecules.common.actions.saveChanges"),
        loading: isSubmitting,
        onClick: submitForm
      })]
    }) : isEditable && /*#__PURE__*/jsxRuntime.jsx("div", {
      children: /*#__PURE__*/jsxRuntime.jsx(Button, {
        "data-cy": "weekly-schedule-header",
        label: t("neetoMolecules.schedule.changeAvailability"),
        style: "primary",
        weight: "semibold",
        onClick: function onClick() {
          return setIsEditing(true);
        }
      })
    })]
  });
};

var css = ".neeto-molecules-schedule{margin:auto;max-width:40rem;width:100%}.neeto-molecules-schedule__dropdown{max-height:var(--neeto-ui-dropdown-popup-max-height)!important}";
injectCss.n(css,{});

var Schedule = /*#__PURE__*/React.forwardRef(function (_ref, scheduleRef) {
  var periods = _ref.periods,
    _ref$handleSubmit = _ref.handleSubmit,
    handleSubmit = _ref$handleSubmit === void 0 ? neetoCist.noop : _ref$handleSubmit,
    _ref$isEditing = _ref.isEditing,
    isEditing = _ref$isEditing === void 0 ? false : _ref$isEditing,
    setIsEditing = _ref.setIsEditing,
    _ref$showHeader = _ref.showHeader,
    showHeader = _ref$showHeader === void 0 ? true : _ref$showHeader,
    _ref$handleValuesChan = _ref.handleValuesChanged,
    handleValuesChanged = _ref$handleValuesChan === void 0 ? neetoCist.noop : _ref$handleValuesChan,
    _ref$allowAddPeriod = _ref.allowAddPeriod,
    allowAddPeriod = _ref$allowAddPeriod === void 0 ? true : _ref$allowAddPeriod,
    _ref$isEditable = _ref.isEditable,
    isEditable = _ref$isEditable === void 0 ? true : _ref$isEditable,
    _ref$isCreating = _ref.isCreating,
    isCreating = _ref$isCreating === void 0 ? false : _ref$isCreating,
    _ref$firstDay = _ref.firstDay,
    firstDay = _ref$firstDay === void 0 ? 1 : _ref$firstDay,
    _ref$showTimeZone = _ref.showTimeZone,
    showTimeZone = _ref$showTimeZone === void 0 ? true : _ref$showTimeZone,
    _ref$slotInterval = _ref.slotInterval,
    slotInterval = _ref$slotInterval === void 0 ? DEFAULT_SLOT_INTERVAL : _ref$slotInterval;
  var validationSchema = React.useMemo(getScheduleValidationSchema, []);
  var getInitialFormValues = function getInitialFormValues() {
    var isSubmitHandler = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : false;
    if (isSubmitHandler) {
      return buildFormValuesArray({
        firstDay: firstDay,
        periods: periods
      });
    }
    return buildFormValuesObject({
      periods: periods
    });
  };
  return /*#__PURE__*/jsxRuntime.jsx(ScheduleContext.Provider, {
    value: {
      allowAddPeriod: allowAddPeriod,
      firstDay: firstDay,
      slotInterval: slotInterval
    },
    children: /*#__PURE__*/jsxRuntime.jsx("div", {
      className: "neeto-molecules-schedule neeto-ui-border-gray-200 flex-shrink-0",
      children: /*#__PURE__*/jsxRuntime.jsx(formik.Formik, {
        validationSchema: validationSchema,
        enableReinitialize: true,
        initialValues: {
          wdays: getInitialFormValues()
        },
        onSubmit: function onSubmit(values) {
          handleSubmit(processFormValues(values, firstDay), getInitialFormValues(true));
        },
        children: /*#__PURE__*/jsxRuntime.jsxs(jsxRuntime.Fragment, {
          children: [showHeader && /*#__PURE__*/jsxRuntime.jsx(Header, {
            isCreating: isCreating,
            isEditable: isEditable,
            isEditing: isEditing,
            setIsEditing: setIsEditing,
            showTimeZone: showTimeZone
          }), isEditing || !showHeader ? /*#__PURE__*/jsxRuntime.jsx(formik.Form, {
            children: /*#__PURE__*/jsxRuntime.jsx(Fields, {
              handleValuesChanged: handleValuesChanged,
              scheduleRef: scheduleRef
            })
          }) : /*#__PURE__*/jsxRuntime.jsx(DisplayAvailability, {
            periods: periods
          })]
        })
      })
    })
  });
});
Schedule.displayName = "Schedule";

exports.addDefaultPeriod = addDefaultPeriod;
exports.buildSlotIntervals = buildSlotIntervals;
exports.default = Schedule;
exports.filterSlots = filterSlots;
exports.formatCreateLabel = formatCreateLabel;
exports.formatTimeSlotOption = formatTimeSlotOption;
exports.generateNewPeriod = generateNewPeriod;
exports.isValidTimeSlotOption = isValidTimeSlotOption;
exports.slotsSelectComponentDefaultValue = slotsSelectComponentDefaultValue;
//# sourceMappingURL=Schedule.js.map
