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/saasDevice/appDevicePlanning/modules/devices/components/AddDeviceModal/index.tsx
var AddDeviceModal_exports = {};
__export(AddDeviceModal_exports, {
  default: () => AddDeviceModal_default
});
module.exports = __toCommonJS(AddDeviceModal_exports);
var import_react = __toESM(require("react"));
var import_antd = require("antd");
var import_materials = require("@pisell/materials");
var import_types = require("../../../../model/types");
var import_constants = require("../../../../model/constants");
var import_api = require("../../../../api");
var import_index = require("./index.less");
var isProfileRequired = (model) => {
  var _a, _b;
  return Boolean((_b = (_a = model == null ? void 0 : model.data) == null ? void 0 : _a.profile_structure) == null ? void 0 : _b.required);
};
var AddDeviceModal = ({
  open,
  variant = "desktop",
  activeKind = "smart",
  model,
  fallbackModelCode,
  workAreaId,
  workAreas,
  submitting,
  preparingShortNumber,
  getText,
  translation,
  onClose,
  onSubmit,
  onPrepareShortNumber
}) => {
  var _a, _b, _c;
  const [form] = import_antd.Form.useForm();
  const [preparedShortNumber, setPreparedShortNumber] = (0, import_react.useState)("");
  const isPhoneVariant = variant === "phone";
  const modelCode = (model == null ? void 0 : model.code) || fallbackModelCode;
  const profileRequired = isProfileRequired(model);
  const profiles = (model == null ? void 0 : model.active_profiles) || [];
  const showShortNumber = activeKind === "smart" || ((_a = model == null ? void 0 : model.type) == null ? void 0 : _a.kind) === "smart";
  (0, import_react.useEffect)(() => {
    if (!open) return;
    setPreparedShortNumber("");
    form.resetFields();
    form.setFieldsValue({
      name: { ...import_types.EMPTY_I18N },
      short_number: "",
      profile_id: void 0,
      workarea_id: workAreaId
    });
  }, [form, open, workAreaId]);
  const fillPreparedShortNumber = async () => {
    const shortNumber = await onPrepareShortNumber();
    setPreparedShortNumber(shortNumber);
    form.setFieldsValue({ short_number: shortNumber });
  };
  (0, import_react.useEffect)(() => {
    if (!open || !showShortNumber) return;
    let cancelled = false;
    const prepare = async () => {
      const shortNumber = await onPrepareShortNumber();
      if (cancelled) return;
      setPreparedShortNumber(shortNumber);
      form.setFieldsValue({ short_number: shortNumber });
    };
    prepare().catch(() => {
    });
    return () => {
      cancelled = true;
    };
  }, [form, onPrepareShortNumber, open, showShortNumber]);
  const handleSave = async () => {
    const values = await form.validateFields();
    const effectiveWorkAreaId = workAreaId || values.workarea_id;
    if (!modelCode || !effectiveWorkAreaId) return;
    const payload = {
      workarea_id: effectiveWorkAreaId,
      model_code: modelCode,
      profile_id: profileRequired ? values.profile_id || null : null,
      name: values.name
    };
    if (showShortNumber) {
      payload.short_number = (0, import_constants.normalizeDeviceShortNumberPayload)(
        values.short_number
      );
    }
    try {
      await onSubmit(payload);
    } catch (error) {
      const currentShortNumber = (0, import_constants.normalizeDeviceShortNumberPayload)(
        values.short_number
      );
      if ((0, import_api.isShortNumberUniqueError)(error) && currentShortNumber === preparedShortNumber) {
        await fillPreparedShortNumber().catch(() => {
        });
      }
    }
  };
  return /* @__PURE__ */ import_react.default.createElement(
    import_materials.PisellModal,
    {
      open,
      onCancel: onClose,
      title: getText("pisell2.saas.device-planning.add.configure-title"),
      footer: /* @__PURE__ */ import_react.default.createElement("div", { className: "add-device-modal__footer", style: { marginTop: 0 } }, /* @__PURE__ */ import_react.default.createElement(import_materials.Button, { type: "default", block: true, size: "large", onClick: onClose }, getText("pisell2.saas.device-planning.add.cancel")), /* @__PURE__ */ import_react.default.createElement(
        import_materials.Button,
        {
          type: "primary",
          block: true,
          size: "large",
          loading: submitting,
          onClick: handleSave
        },
        getText("pisell2.saas.device-planning.add.save")
      )),
      destroyOnClose: true,
      maskClosable: false,
      width: 480,
      platform: isPhoneVariant ? "h5" : void 0,
      mobileModalHeight: isPhoneVariant ? "auto" : void 0,
      className: `add-device-modal add-device-modal--${variant}`,
      bodyStyle: { padding: "24px" }
    },
    /* @__PURE__ */ import_react.default.createElement("div", { className: "add-device-modal__body" }, /* @__PURE__ */ import_react.default.createElement("div", { className: "add-device-modal__selected-model" }, ((_b = model == null ? void 0 : model.type) == null ? void 0 : _b.icon) ? /* @__PURE__ */ import_react.default.createElement(import_materials.Icon, { type: (_c = model == null ? void 0 : model.type) == null ? void 0 : _c.icon, style: { marginTop: "4px" } }) : null, /* @__PURE__ */ import_react.default.createElement("div", null, /* @__PURE__ */ import_react.default.createElement("div", { className: "add-device-modal__model-name" }, translation(model == null ? void 0 : model.name) || modelCode || "-"), /* @__PURE__ */ import_react.default.createElement("div", { className: "add-device-modal__model-desc" }, translation(model == null ? void 0 : model.description) || modelCode || "-"))), /* @__PURE__ */ import_react.default.createElement(import_antd.Form, { form, layout: "vertical", preserve: false }, !workAreaId ? /* @__PURE__ */ import_react.default.createElement(
      import_antd.Form.Item,
      {
        name: "workarea_id",
        label: getText("pisell2.saas.device-planning.edit.work-area"),
        required: true,
        rules: [
          {
            required: true,
            message: getText(
              "pisell2.saas.device-planning.edit.work-area-required"
            )
          }
        ]
      },
      /* @__PURE__ */ import_react.default.createElement(
        import_antd.Select,
        {
          placeholder: getText(
            "pisell2.saas.device-planning.add.work-area-placeholder"
          ),
          options: workAreas.map((item) => ({
            label: translation(item.name),
            value: item.id
          }))
        }
      )
    ) : null, /* @__PURE__ */ import_react.default.createElement(
      import_antd.Form.Item,
      {
        name: "name",
        label: getText("pisell2.saas.device-planning.add.device-name"),
        required: true,
        rules: [
          {
            validator: (0, import_types.validateI18nRequired)(
              getText(
                "pisell2.saas.device-planning.add.device-name-required"
              )
            )
          }
        ]
      },
      /* @__PURE__ */ import_react.default.createElement(
        import_materials.BaseTranslation,
        {
          renderMode: "edit",
          placeholder: getText(
            "pisell2.saas.device-planning.add.device-name-placeholder"
          )
        }
      )
    ), showShortNumber ? /* @__PURE__ */ import_react.default.createElement(
      import_antd.Form.Item,
      {
        name: "short_number",
        label: getText(
          "pisell2.saas.device-planning.device-short-number.label"
        ),
        normalize: (value) => (0, import_constants.normalizeDeviceShortNumberInput)(value),
        required: true,
        rules: [
          {
            validator: (0, import_constants.validateDeviceShortNumber)({
              required: getText(
                "pisell2.saas.device-planning.device-short-number.required"
              ),
              format: getText(
                "pisell2.saas.device-planning.device-short-number.format"
              ),
              reserved: getText(
                "pisell2.saas.device-planning.device-short-number.reserved"
              )
            })
          }
        ],
        extra: getText(
          "pisell2.saas.device-planning.device-short-number.helper"
        )
      },
      /* @__PURE__ */ import_react.default.createElement(
        import_antd.Input,
        {
          maxLength: import_constants.DEVICE_SHORT_NUMBER_MAX_LENGTH,
          placeholder: getText(
            "pisell2.saas.device-planning.device-short-number.placeholder"
          )
        }
      )
    ) : null, profileRequired ? /* @__PURE__ */ import_react.default.createElement(
      import_antd.Form.Item,
      {
        name: "profile_id",
        label: getText("pisell2.saas.device-planning.add.device-profile"),
        required: true,
        rules: [
          {
            required: true,
            message: getText(
              "pisell2.saas.device-planning.add.device-profile-required"
            )
          }
        ],
        help: profiles.length === 0 ? getText(
          "pisell2.saas.device-planning.add.create-profile-first"
        ) : void 0
      },
      /* @__PURE__ */ import_react.default.createElement(
        import_antd.Select,
        {
          disabled: profiles.length === 0,
          placeholder: getText(
            "pisell2.saas.device-planning.add.device-profile-placeholder"
          ),
          options: profiles.map((profile) => ({
            label: translation(profile.name) || String(profile.id),
            value: profile.id
          }))
        }
      )
    ) : null))
  );
};
var AddDeviceModal_default = AddDeviceModal;
