var __create = Object.create;
var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
var __getProtoOf = Object.getPrototypeOf;
var __hasOwnProp = Object.prototype.hasOwnProperty;
var __export = (target, all) => {
  for (var name in all)
    __defProp(target, name, { get: all[name], enumerable: true });
};
var __copyProps = (to, from, except, desc) => {
  if (from && typeof from === "object" || typeof from === "function") {
    for (let key of __getOwnPropNames(from))
      if (!__hasOwnProp.call(to, key) && key !== except)
        __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
  }
  return to;
};
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
  // If the importer is in node compatibility mode or this is not an ESM
  // file that has been converted to a CommonJS file using a Babel-
  // compatible transform (i.e. "__esModule" has not been set), then set
  // "default" to the CommonJS "module.exports" for node compatibility.
  isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
  mod
));
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);

// src/plus/saasAttendance/settings/components/shiftModal/index.tsx
var shiftModal_exports = {};
__export(shiftModal_exports, {
  default: () => shiftModal_default
});
module.exports = __toCommonJS(shiftModal_exports);
var import_react = __toESM(require("react"));
var import_antd = require("antd");
var import_icons = require("@ant-design/icons");
var import_materials = require("@pisell/materials");
var import_utils = require("@pisell/utils");
var import_dayjs = __toESM(require("dayjs"));
var WEEKDAYS = [1, 2, 3, 4, 5, 6, 7];
var AntRow = import_antd.Row;
var AntCol = import_antd.Col;
var AntSpace = import_antd.Space;
var generateUUID = () => {
  return "xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g, (c) => {
    const r = Math.random() * 16 | 0;
    const v = c === "x" ? r : r & 3 | 8;
    return v.toString(16);
  });
};
var pad2 = (val) => String(val).padStart(2, "0");
var createTime = (hour, minute) => {
  return (0, import_dayjs.default)().hour(hour).minute(minute).second(0).millisecond(0);
};
var toMinutes = (val) => val.hour() * 60 + val.minute();
var parseHHmm = (hhmm) => {
  const [h, m] = (hhmm || "").split(":").map((v) => Number(v));
  if (!Number.isFinite(h) || !Number.isFinite(m)) {
    return null;
  }
  return createTime(h, m);
};
var formatHHmm = (val) => `${pad2(val.hour())}:${pad2(val.minute())}`;
var buildInitialDays = (value) => {
  const byWeekday = /* @__PURE__ */ new Map();
  if (Array.isArray(value)) {
    value.forEach((item) => {
      if (item && typeof item.weekday === "number") {
        byWeekday.set(item.weekday, item);
      }
    });
  }
  return WEEKDAYS.map((weekday) => {
    const src = byWeekday.get(weekday);
    const times = Array.isArray(src == null ? void 0 : src.times) ? src.times : [];
    return {
      weekday,
      enabled: times.length > 0,
      times: times.map((t) => {
        return {
          id: (t == null ? void 0 : t.id) || generateUUID(),
          start: (t == null ? void 0 : t.start) ? parseHHmm(t.start) : null,
          end: (t == null ? void 0 : t.end) ? parseHHmm(t.end) : null
        };
      })
    };
  });
};
var getWeekdayText = (weekday) => {
  return import_utils.locales.getText(
    `pisell2.attendance.group-settings.shift-schedule.modal.weekday.${weekday}`
  );
};
var ShiftModal = (props) => {
  const [form] = import_antd.Form.useForm();
  (0, import_react.useEffect)(() => {
    if (!props.open) return;
    form.setFieldsValue({ days: buildInitialDays(props.value) });
  }, [form, props.open, props.value]);
  const isTimeOverlapping = (dayIndex, timeIndex) => {
    const times = form.getFieldValue(["days", dayIndex, "times"]) || [];
    const cur = times == null ? void 0 : times[timeIndex];
    if (!(cur == null ? void 0 : cur.start) || !(cur == null ? void 0 : cur.end)) return false;
    const curStart = toMinutes(cur.start);
    const curEnd = toMinutes(cur.end);
    if (curStart >= curEnd) return false;
    for (let i = 0; i < times.length; i += 1) {
      if (i === timeIndex) continue;
      const other = times[i];
      if (!(other == null ? void 0 : other.start) || !(other == null ? void 0 : other.end)) continue;
      const oStart = toMinutes(other.start);
      const oEnd = toMinutes(other.end);
      if (oStart >= oEnd) continue;
      const overlapped = curStart <= oEnd && oStart <= curEnd;
      if (overlapped) return true;
    }
    return false;
  };
  const triggerDayValidation = (dayIndex) => {
    const times = form.getFieldValue(["days", dayIndex, "times"]) || [];
    const fields = [];
    times.forEach((t, idx) => {
      if (t == null ? void 0 : t.start) fields.push(["days", dayIndex, "times", idx, "start"]);
      if (t == null ? void 0 : t.end) fields.push(["days", dayIndex, "times", idx, "end"]);
    });
    if (!fields.length) return;
    form.validateFields(fields).catch(() => {
    });
  };
  const toScheduleValue = (days) => {
    const byWeekday = /* @__PURE__ */ new Map();
    days.forEach((d) => {
      if (d && typeof d.weekday === "number") {
        byWeekday.set(d.weekday, d);
      }
    });
    return WEEKDAYS.map((weekday) => {
      const day = byWeekday.get(weekday);
      if (!(day == null ? void 0 : day.enabled)) {
        return { weekday, times: [] };
      }
      const times = Array.isArray(day.times) ? day.times : [];
      const normalized = times.filter((t) => (t == null ? void 0 : t.start) && (t == null ? void 0 : t.end)).map((t) => ({
        id: t.id || generateUUID(),
        start: formatHHmm(t.start),
        end: formatHHmm(t.end),
        startSort: toMinutes(t.start)
      })).sort((a, b) => a.startSort - b.startSort).map(({ startSort: _startSort, ...rest }) => rest);
      return {
        weekday,
        times: normalized
      };
    });
  };
  const handleConfirm = async () => {
    let values;
    try {
      values = await form.validateFields();
    } catch {
      return;
    }
    const days = Array.isArray(values == null ? void 0 : values.days) ? values.days : [];
    props.onOk(toScheduleValue(days));
    props.onCancel();
  };
  const footer = (0, import_react.useMemo)(() => {
    return /* @__PURE__ */ import_react.default.createElement(AntSpace, { style: { width: "100%", justifyContent: "flex-end" } }, /* @__PURE__ */ import_react.default.createElement(import_antd.Button, { onClick: props.onCancel }, import_utils.locales.getText("pisell2.attendance.group-settings.actions.cancel")), /* @__PURE__ */ import_react.default.createElement(import_antd.Button, { type: "primary", onClick: handleConfirm }, import_utils.locales.getText("pisell2.attendance.group-settings.actions.confirm")));
  }, [handleConfirm, props.onCancel]);
  return /* @__PURE__ */ import_react.default.createElement(
    import_materials.PisellModal,
    {
      open: props.open,
      onCancel: props.onCancel,
      title: import_utils.locales.getText(
        "pisell2.attendance.group-settings.shift-schedule.modal.title"
      ),
      width: 720,
      bodyStyle: { padding: 20 },
      footer,
      destroyOnClose: true
    },
    /* @__PURE__ */ import_react.default.createElement(import_antd.Form, { form, layout: "vertical" }, /* @__PURE__ */ import_react.default.createElement(import_antd.Form.List, { name: "days" }, (dayFields) => /* @__PURE__ */ import_react.default.createElement("div", null, dayFields.map((dayField, dayIndex) => {
      return /* @__PURE__ */ import_react.default.createElement("div", { key: dayField.key, style: { padding: "12px 0" } }, /* @__PURE__ */ import_react.default.createElement(AntRow, { gutter: 12, align: "top" }, /* @__PURE__ */ import_react.default.createElement(AntCol, { flex: "180px" }, /* @__PURE__ */ import_react.default.createElement(
        import_antd.Form.Item,
        {
          name: [dayField.name, "enabled"],
          valuePropName: "checked",
          style: { marginBottom: 0 }
        },
        /* @__PURE__ */ import_react.default.createElement(
          import_antd.Checkbox,
          {
            onChange: (e) => {
              const checked = e.target.checked;
              const timesPath = [
                "days",
                dayIndex,
                "times"
              ];
              if (checked) {
                const current = form.getFieldValue(timesPath) || [];
                if (!current.length) {
                  form.setFieldValue(timesPath, [
                    {
                      id: generateUUID(),
                      start: null,
                      end: null
                    }
                  ]);
                }
              } else {
                form.setFieldValue(timesPath, []);
              }
            }
          },
          getWeekdayText(dayIndex + 1)
        )
      ), /* @__PURE__ */ import_react.default.createElement(import_antd.Form.Item, { name: [dayField.name, "weekday"], hidden: true }, /* @__PURE__ */ import_react.default.createElement(import_antd.Input, null))), /* @__PURE__ */ import_react.default.createElement(AntCol, { flex: "auto" }, /* @__PURE__ */ import_react.default.createElement(
        import_antd.Form.Item,
        {
          noStyle: true,
          shouldUpdate: (prev, cur) => {
            var _a, _b, _c, _d, _e, _f, _g, _h;
            return ((_b = (_a = prev == null ? void 0 : prev.days) == null ? void 0 : _a[dayIndex]) == null ? void 0 : _b.enabled) !== ((_d = (_c = cur == null ? void 0 : cur.days) == null ? void 0 : _c[dayIndex]) == null ? void 0 : _d.enabled) || ((_f = (_e = prev == null ? void 0 : prev.days) == null ? void 0 : _e[dayIndex]) == null ? void 0 : _f.times) !== ((_h = (_g = cur == null ? void 0 : cur.days) == null ? void 0 : _g[dayIndex]) == null ? void 0 : _h.times);
          }
        },
        () => {
          const enabled = form.getFieldValue([
            "days",
            dayIndex,
            "enabled"
          ]);
          if (!enabled) {
            return /* @__PURE__ */ import_react.default.createElement(
              "div",
              {
                style: {
                  lineHeight: "40px",
                  color: "#6b7280"
                }
              },
              import_utils.locales.getText(
                "pisell2.attendance.group-settings.shift-schedule.modal.no-shift"
              )
            );
          }
          return /* @__PURE__ */ import_react.default.createElement(import_antd.Form.List, { name: [dayField.name, "times"] }, (timeFields, { add, remove }) => /* @__PURE__ */ import_react.default.createElement("div", null, timeFields.map((timeField, timeIndex) => {
            return /* @__PURE__ */ import_react.default.createElement(
              AntRow,
              {
                key: timeField.key,
                gutter: 8,
                style: { marginBottom: 8 }
              },
              /* @__PURE__ */ import_react.default.createElement(AntCol, { flex: "1 1 220px" }, /* @__PURE__ */ import_react.default.createElement(
                import_antd.Form.Item,
                {
                  name: [timeField.name, "id"],
                  hidden: true
                },
                /* @__PURE__ */ import_react.default.createElement(import_antd.Input, null)
              ), /* @__PURE__ */ import_react.default.createElement(
                import_antd.Form.Item,
                {
                  label: timeIndex === 0 ? import_utils.locales.getText(
                    "pisell2.attendance.group-settings.shift-schedule.modal.start"
                  ) : void 0,
                  name: [timeField.name, "start"],
                  rules: [
                    {
                      validator: async (_rule, value) => {
                        if (!value) {
                          throw new Error(
                            import_utils.locales.getText(
                              "pisell2.attendance.group-settings.shift-schedule.modal.validation.start-required"
                            )
                          );
                        }
                        if (isTimeOverlapping(
                          dayIndex,
                          timeField.name
                        )) {
                          throw new Error(
                            import_utils.locales.getText(
                              "pisell2.attendance.group-settings.shift-schedule.modal.validation.overlap"
                            )
                          );
                        }
                      }
                    }
                  ]
                },
                /* @__PURE__ */ import_react.default.createElement(
                  import_antd.TimePicker,
                  {
                    use12Hours: true,
                    format: "h:mm A",
                    style: { width: "100%" },
                    onChange: () => {
                      triggerDayValidation(
                        dayIndex
                      );
                      form.validateFields([
                        [
                          "days",
                          dayIndex,
                          "times",
                          timeField.name,
                          "end"
                        ]
                      ]).catch(() => {
                      });
                    }
                  }
                )
              )),
              /* @__PURE__ */ import_react.default.createElement(AntCol, { flex: "1 1 220px" }, /* @__PURE__ */ import_react.default.createElement(
                import_antd.Form.Item,
                {
                  label: timeIndex === 0 ? import_utils.locales.getText(
                    "pisell2.attendance.group-settings.shift-schedule.modal.end"
                  ) : void 0,
                  name: [timeField.name, "end"],
                  rules: [
                    {
                      validator: async (_rule, value) => {
                        if (!value) {
                          throw new Error(
                            import_utils.locales.getText(
                              "pisell2.attendance.group-settings.shift-schedule.modal.validation.end-required"
                            )
                          );
                        }
                        const startValue = form.getFieldValue([
                          "days",
                          dayIndex,
                          "times",
                          timeField.name,
                          "start"
                        ]) || null;
                        if (startValue && toMinutes(startValue) >= toMinutes(value)) {
                          throw new Error(
                            import_utils.locales.getText(
                              "pisell2.attendance.group-settings.shift-schedule.modal.validation.range"
                            )
                          );
                        }
                      }
                    }
                  ]
                },
                /* @__PURE__ */ import_react.default.createElement(
                  import_antd.TimePicker,
                  {
                    use12Hours: true,
                    format: "h:mm A",
                    style: { width: "100%" },
                    onChange: () => {
                      triggerDayValidation(
                        dayIndex
                      );
                    }
                  }
                )
              )),
              /* @__PURE__ */ import_react.default.createElement(AntCol, { flex: "0 0 40px" }, timeIndex === 0 ? /* @__PURE__ */ import_react.default.createElement("div", { style: { height: 48 } }) : null, /* @__PURE__ */ import_react.default.createElement(
                import_antd.Button,
                {
                  icon: /* @__PURE__ */ import_react.default.createElement(import_icons.DeleteOutlined, null),
                  onClick: () => {
                    remove(timeField.name);
                    triggerDayValidation(dayIndex);
                    const left = form.getFieldValue([
                      "days",
                      dayIndex,
                      "times"
                    ]) || [];
                    if (!left.length) {
                      form.setFieldValue(
                        [
                          "days",
                          dayIndex,
                          "enabled"
                        ],
                        false
                      );
                    }
                  }
                }
              ))
            );
          }), /* @__PURE__ */ import_react.default.createElement(
            import_antd.Button,
            {
              icon: /* @__PURE__ */ import_react.default.createElement(import_icons.PlusOutlined, null),
              onClick: () => {
                const times = form.getFieldValue([
                  "days",
                  dayIndex,
                  "times"
                ]) || [];
                const last = times[times.length - 1];
                if (!(last == null ? void 0 : last.start) || !(last == null ? void 0 : last.end)) {
                  add({
                    id: generateUUID(),
                    start: null,
                    end: null
                  });
                  triggerDayValidation(dayIndex);
                  return;
                }
                const lastEnd = last.end;
                const endDateText = lastEnd.format("YYYY-MM-DD");
                const nextStart = lastEnd.add(
                  1,
                  "hour"
                );
                const nextEnd = lastEnd.add(2, "hour");
                const crossed = nextEnd.format("YYYY-MM-DD") !== endDateText || nextStart.format("YYYY-MM-DD") !== endDateText;
                if (crossed) {
                  add({
                    id: generateUUID(),
                    start: createTime(23, 0),
                    end: createTime(23, 55)
                  });
                  triggerDayValidation(dayIndex);
                  return;
                }
                add({
                  id: generateUUID(),
                  start: nextStart,
                  end: nextEnd
                });
                triggerDayValidation(dayIndex);
              }
            },
            import_utils.locales.getText(
              "pisell2.attendance.group-settings.shift-schedule.modal.add-time"
            )
          )));
        }
      ))));
    }))))
  );
};
var shiftModal_default = ShiftModal;
