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/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_types = require("../../types");
var import_constants = require("../../constants");
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 hasI18nValue = (value) => {
  if (!value) return false;
  return Object.values(value).some((item) => String(item || "").trim());
};
var AddDeviceModal = ({
  open,
  activeKind,
  models,
  workAreaId,
  submitting,
  getText,
  translation,
  onClose,
  onSubmit
}) => {
  const [form] = import_antd.Form.useForm();
  const [step, setStep] = (0, import_react.useState)("model");
  const [keyword, setKeyword] = (0, import_react.useState)("");
  const [selectedModel, setSelectedModel] = (0, import_react.useState)();
  const nameValue = import_antd.Form.useWatch("name", form);
  const profileValue = import_antd.Form.useWatch("profile_id", form);
  (0, import_react.useEffect)(() => {
    if (!open) return;
    setStep("model");
    setKeyword("");
    setSelectedModel(void 0);
    form.resetFields();
    form.setFieldsValue({ name: { ...import_types.EMPTY_I18N } });
  }, [form, open]);
  const filteredModels = (0, import_react.useMemo)(() => {
    const value = (0, import_constants.normalizeText)(keyword);
    if (!value) return models;
    return models.filter((model) => {
      const name = translation(model.name);
      const desc = translation(model.description);
      return [name, desc, model.code, model.type_code].some(
        (item) => (0, import_constants.normalizeText)(item || "").includes(value)
      );
    });
  }, [keyword, models, translation]);
  const groupedModels = (0, import_react.useMemo)(() => {
    const groups = /* @__PURE__ */ new Map();
    filteredModels.forEach((model) => {
      const key = model.type_code || getText(import_constants.DEVICE_KIND_LABEL_KEY[activeKind]);
      groups.set(key, [...groups.get(key) || [], model]);
    });
    return Array.from(groups.entries());
  }, [activeKind, filteredModels, getText]);
  const profileRequired = isProfileRequired(selectedModel);
  const profiles = (selectedModel == null ? void 0 : selectedModel.active_profiles) || [];
  const canSave = Boolean(
    workAreaId && selectedModel && hasI18nValue(nameValue) && (!profileRequired || profiles.length > 0) && (!profileRequired || Boolean(profileValue))
  );
  const handleSelectModel = (model) => {
    setSelectedModel(model);
    setStep("configure");
    form.resetFields();
    form.setFieldsValue({ name: { ...import_types.EMPTY_I18N }, profile_id: void 0 });
  };
  const handleSave = async () => {
    if (!canSave || !selectedModel || !workAreaId) return;
    const values = await form.validateFields();
    onSubmit({
      workarea_id: workAreaId,
      model_code: selectedModel.code,
      profile_id: profileRequired ? values.profile_id || null : null,
      name: values.name
    });
  };
  const renderModelStep = () => /* @__PURE__ */ import_react.default.createElement("div", { className: "add-device-modal__body" }, /* @__PURE__ */ import_react.default.createElement(
    import_materials.Input,
    {
      allowClear: true,
      prefix: /* @__PURE__ */ import_react.default.createElement(import_icons.SearchOutlined, null),
      value: keyword,
      placeholder: getText("pisell2.saas.device-planning.add.search"),
      onChange: (event) => setKeyword(event.target.value)
    }
  ), /* @__PURE__ */ import_react.default.createElement("div", { className: "add-device-modal__model-list" }, groupedModels.length ? groupedModels.map(([typeCode, items]) => {
    var _a;
    const type = (_a = items[0]) == null ? void 0 : _a.type;
    const typeName = translation(type == null ? void 0 : type.name) || typeCode;
    return /* @__PURE__ */ import_react.default.createElement("div", { key: typeCode, className: "add-device-modal__model-group" }, /* @__PURE__ */ import_react.default.createElement("div", { className: "add-device-modal__group-title" }, (type == null ? void 0 : type.icon) ? /* @__PURE__ */ import_react.default.createElement(import_materials.Icon, { type: type == null ? void 0 : type.icon }) : null, /* @__PURE__ */ import_react.default.createElement("span", null, typeName)), /* @__PURE__ */ import_react.default.createElement("div", { className: "add-device-modal__model-grid" }, items.map((model) => /* @__PURE__ */ import_react.default.createElement(
      "div",
      {
        key: model.code,
        className: (0, import_classnames.default)("add-device-modal__model-card", {
          "is-selected": (selectedModel == null ? void 0 : selectedModel.code) === model.code
        }),
        onClick: () => handleSelectModel(model)
      },
      /* @__PURE__ */ import_react.default.createElement("div", { className: "add-device-modal__model-name" }, translation(model.name) || ""),
      /* @__PURE__ */ import_react.default.createElement("div", { className: "add-device-modal__model-desc" }, translation(model.description) || "")
    ))));
  }) : /* @__PURE__ */ import_react.default.createElement(
    import_materials.Empty,
    {
      image: import_materials.Empty.PRESENTED_IMAGE_SIMPLE,
      description: /* @__PURE__ */ import_react.default.createElement("div", null, /* @__PURE__ */ import_react.default.createElement("div", null, getText("pisell2.saas.device-planning.add.no-devices")), /* @__PURE__ */ import_react.default.createElement("div", null, getText("pisell2.saas.device-planning.add.adjust-search")))
    }
  )));
  const renderConfigureStep = () => {
    var _a;
    return /* @__PURE__ */ import_react.default.createElement("div", { className: "add-device-modal__body" }, selectedModel ? /* @__PURE__ */ import_react.default.createElement("div", { className: "add-device-modal__selected-model" }, /* @__PURE__ */ import_react.default.createElement(import_materials.Icon, { type: ((_a = selectedModel.type) == null ? void 0 : _a.icon) || "DesktopOutlined" }), /* @__PURE__ */ import_react.default.createElement("div", null, /* @__PURE__ */ import_react.default.createElement("div", { className: "add-device-modal__model-name" }, translation(selectedModel.name) || ""), /* @__PURE__ */ import_react.default.createElement("div", { className: "add-device-modal__model-desc" }, translation(selectedModel.description) || ""))) : null, /* @__PURE__ */ import_react.default.createElement(import_antd.Form, { form, layout: "vertical", preserve: false }, /* @__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" })
    ), 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_materials.Select,
        {
          disabled: profiles.length === 0,
          options: profiles.map((profile) => ({
            label: translation(profile.name) || String(profile.id),
            value: profile.id
          }))
        }
      )
    ) : null));
  };
  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"),
      footer: null,
      destroyOnClose: true,
      maskClosable: false,
      width: step === "model" ? 760 : 480,
      className: "add-device-modal",
      bodyStyle: { padding: "24px" }
    },
    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: () => setStep("model")
      }
    ) : null,
    step === "model" ? renderModelStep() : renderConfigureStep(),
    /* @__PURE__ */ import_react.default.createElement("div", { className: "add-device-modal__footer" }, step === "model" ? /* @__PURE__ */ import_react.default.createElement(import_materials.Button, { type: "text", onClick: onClose }, getText("pisell2.saas.device-planning.add.cancel")) : /* @__PURE__ */ import_react.default.createElement(import_react.default.Fragment, null, /* @__PURE__ */ import_react.default.createElement(import_materials.Button, { type: "text", onClick: () => setStep("model") }, getText("pisell2.saas.device-planning.add.back")), /* @__PURE__ */ import_react.default.createElement(
      import_materials.Button,
      {
        type: "primary",
        disabled: !canSave,
        loading: submitting,
        onClick: handleSave
      },
      getText("pisell2.saas.device-planning.add.save")
    )))
  );
};
var AddDeviceModal_default = AddDeviceModal;
