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/devicePlanning/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_icons = require("@ant-design/icons");
var import_classnames = __toESM(require("classnames"));
var import_model = require("../../../../model");
var import_api = require("../../../../api");
var import_shared = require("../../../../shared");
var import_DeviceBasicInfoForm = __toESM(require("../../../../components/shared/DeviceBasicInfoForm"));
var import_DeviceModelPicker = __toESM(require("../../../../components/shared/DeviceModelPicker"));
var import_index = require("./index.less");
var AddDeviceModal = ({
  open,
  activeKind,
  models,
  brands = [],
  workAreaId,
  submitting,
  preparingShortNumber,
  getText,
  translation,
  onClose,
  onSubmit,
  onPrepareShortNumber
}) => {
  const [form] = import_antd.Form.useForm();
  const [step, setStep] = (0, import_react.useState)("model");
  const [selectedModel, setSelectedModel] = (0, import_react.useState)();
  const [preparedShortNumber, setPreparedShortNumber] = (0, import_react.useState)("");
  const isPeripheral = activeKind === "dumb";
  const isSmartDevice = activeKind === "smart";
  (0, import_react.useEffect)(() => {
    if (!open) return;
    setStep("model");
    setSelectedModel(void 0);
    setPreparedShortNumber("");
    form.resetFields();
    form.setFieldsValue({
      name: { ...import_model.EMPTY_I18N },
      description: { ...import_model.EMPTY_I18N },
      short_number: ""
    });
  }, [form, open]);
  const profileRequired = (0, import_shared.isProfileRequired)(selectedModel);
  const profiles = (selectedModel == null ? void 0 : selectedModel.active_profiles) || [];
  const fillPreparedShortNumber = async () => {
    const shortNumber = await onPrepareShortNumber();
    setPreparedShortNumber(shortNumber);
    form.setFieldsValue({ short_number: shortNumber });
  };
  (0, import_react.useEffect)(() => {
    if (!open || !isSmartDevice || step !== "configure") 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, isSmartDevice, onPrepareShortNumber, open, step]);
  const backToModelStep = () => {
    setPreparedShortNumber("");
    setStep("model");
  };
  const handleSelectModel = (model) => {
    setSelectedModel(model);
    setStep("configure");
    setPreparedShortNumber("");
    form.resetFields();
    form.setFieldsValue({
      name: { ...import_model.EMPTY_I18N },
      description: { ...import_model.EMPTY_I18N },
      profile_id: void 0,
      short_number: ""
    });
  };
  const handleSave = async () => {
    if (!selectedModel || !workAreaId) return;
    const values = await form.validateFields();
    const payload = {
      workarea_id: workAreaId,
      model_code: selectedModel.code,
      profile_id: profileRequired ? values.profile_id || null : null,
      name: values.name,
      description: values.description
    };
    if (isSmartDevice) {
      payload.short_number = (0, import_model.normalizeDeviceShortNumberPayload)(
        values.short_number
      );
    }
    try {
      await onSubmit(payload);
    } catch (error) {
      const currentShortNumber = (0, import_model.normalizeDeviceShortNumberPayload)(
        values.short_number
      );
      if ((0, import_api.isShortNumberUniqueError)(error) && currentShortNumber === preparedShortNumber) {
        await fillPreparedShortNumber().catch(() => {
        });
      }
    }
  };
  const renderModelStep = () => /* @__PURE__ */ import_react.default.createElement(
    import_DeviceModelPicker.default,
    {
      activeKind,
      models,
      brands,
      getText,
      translation,
      onSelect: handleSelectModel
    }
  );
  const renderConfigureStep = () => /* @__PURE__ */ import_react.default.createElement(
    import_DeviceBasicInfoForm.default,
    {
      form,
      selectedModel,
      profiles,
      profileRequired,
      showProfile: true,
      showShortNumber: isSmartDevice,
      getText,
      translation
    }
  );
  return /* @__PURE__ */ import_react.default.createElement(
    import_materials.PisellModal,
    {
      open,
      onCancel: onClose,
      title: step === "model" ? getText(`pisell2.saas.device-planning.add.title.${activeKind}`) : getText("pisell2.saas.device-planning.add.configure-title"),
      okVisible: step === "configure",
      okText: getText("pisell2.saas.device-planning.add.save"),
      cancelText: getText(
        step === "model" ? "pisell2.saas.device-planning.add.cancel" : "pisell2.saas.device-planning.add.back"
      ),
      okButtonProps: {
        block: true,
        size: "large",
        loading: submitting,
        onClick: handleSave
      },
      cancelButtonProps: {
        block: true,
        size: "large",
        type: "default",
        onClick: step === "model" ? onClose : backToModelStep
      },
      destroyOnClose: true,
      maskClosable: false,
      width: step === "model" ? "980px" : "480px",
      className: (0, import_classnames.default)("add-device-modal", {
        "is-peripheral": isPeripheral && step === "model"
      }),
      bodyStyle: { padding: "24px", overflow: step === "model" ? "hidden" : "auto" }
    },
    step === "configure" ? /* @__PURE__ */ import_react.default.createElement(
      import_materials.Button,
      {
        type: "text",
        icon: /* @__PURE__ */ import_react.default.createElement(import_icons.ArrowLeftOutlined, null),
        className: "add-device-modal__back-icon",
        onClick: backToModelStep
      }
    ) : null,
    step === "model" ? renderModelStep() : renderConfigureStep()
  );
};
var AddDeviceModal_default = AddDeviceModal;
