var __defProp = Object.defineProperty;
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
var __getOwnPropNames = Object.getOwnPropertyNames;
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 __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);

// src/plus/saasDevice/devicePlanning/components/DeviceDetailDrawer/hooks/useConnectDeviceModal.ts
var useConnectDeviceModal_exports = {};
__export(useConnectDeviceModal_exports, {
  useConnectDeviceModal: () => useConnectDeviceModal
});
module.exports = __toCommonJS(useConnectDeviceModal_exports);
var import_react = require("react");
var import_serve = require("../../../serve");
var import_types = require("../../../types");
var import_constants = require("../../../constants");
var import_utils = require("../../../utils");
var needsNetworkConfig = (connectionType) => connectionType === "ethernet" || connectionType === "wifi";
var useConnectDeviceModal = ({
  open,
  mode,
  currentDevice,
  editConnection,
  connectedDeviceIds,
  currentWorkAreaId,
  getText,
  translation,
  onSubmit,
  onUpdate
}) => {
  const [step, setStep] = (0, import_react.useState)("pick");
  const [workAreas, setWorkAreas] = (0, import_react.useState)([]);
  const [selectedWorkAreaId, setSelectedWorkAreaId] = (0, import_react.useState)();
  const [devices, setDevices] = (0, import_react.useState)([]);
  const [models, setModels] = (0, import_react.useState)([]);
  const [brands, setBrands] = (0, import_react.useState)([]);
  const [selectedDevice, setSelectedDevice] = (0, import_react.useState)();
  const [selectedModel, setSelectedModel] = (0, import_react.useState)();
  const [keyword, setKeyword] = (0, import_react.useState)("");
  const [editFormValues, setEditFormValues] = (0, import_react.useState)();
  const [loading, setLoading] = (0, import_react.useState)(false);
  const [detailLoading, setDetailLoading] = (0, import_react.useState)(false);
  const [pickingDeviceId, setPickingDeviceId] = (0, import_react.useState)();
  const currentIsSmart = currentDevice.type_kind === "smart";
  const targetKind = currentIsSmart ? "dumb" : "smart";
  const peripheral = currentIsSmart && mode === "new" ? void 0 : currentIsSmart ? selectedDevice : currentDevice;
  const smartDevice = currentIsSmart ? currentDevice : selectedDevice;
  const fallbackProfileModel = (peripheral == null ? void 0 : peripheral.model_code) ? models.find((model) => model.code === peripheral.model_code) : void 0;
  const profileSource = mode === "new" ? selectedModel : (peripheral == null ? void 0 : peripheral.model) || fallbackProfileModel;
  const profileOptions = ((profileSource == null ? void 0 : profileSource.active_profiles) || []).map((profile) => ({
    label: translation(profile.name) || String(profile.id),
    value: profile.id
  }));
  const profileRequired = (0, import_utils.isProfileRequired)(profileSource);
  const getWorkAreaDeviceCount = (area) => targetKind === "smart" ? area.smart_devices_count || 0 : area.dumb_devices_count || 0;
  const getDeviceCountText = (count) => {
    const key = targetKind === "smart" ? count === 1 ? "pisell2.saas.device-planning.connect.smart-count-one" : "pisell2.saas.device-planning.connect.smart-count-many" : count === 1 ? "pisell2.saas.device-planning.connect.peripheral-count-one" : "pisell2.saas.device-planning.connect.peripheral-count-many";
    return getText(key).replace("{N}", String(count));
  };
  (0, import_react.useEffect)(() => {
    if (!open) return;
    setStep(mode === "edit" ? "config" : "pick");
    setSelectedDevice(void 0);
    setSelectedModel(void 0);
    setKeyword("");
    setEditFormValues(void 0);
    setPickingDeviceId(void 0);
    setLoading(true);
    setDetailLoading(mode === "edit");
    Promise.all([
      (0, import_serve.getWorkAreas)(),
      mode === "new" ? (0, import_serve.getDeviceBrands)() : Promise.resolve([]),
      (0, import_serve.getDeviceTypes)({
        kind: "dumb",
        with: ["activeModels", "activeModels.activeProfiles", "activeModels.brand"]
      }),
      mode === "edit" && (editConnection == null ? void 0 : editConnection.id) ? (0, import_serve.getDeviceConnectionDetail)(editConnection.id) : Promise.resolve(null)
    ]).then(([areas, brandList, types, detail]) => {
      var _a, _b, _c, _d;
      setWorkAreas(areas);
      setBrands(brandList);
      setModels((0, import_utils.flattenDeviceModels)(types));
      const defaultWorkAreaId = currentWorkAreaId || ((_a = areas[0]) == null ? void 0 : _a.id);
      setSelectedWorkAreaId(defaultWorkAreaId);
      if (detail) {
        setSelectedDevice(
          currentIsSmart ? detail.target_device || void 0 : detail.source_device || void 0
        );
        setEditFormValues({
          connection_type: (_b = detail.config) == null ? void 0 : _b.connection_type,
          connection_method: ((_c = detail.config) == null ? void 0 : _c.connection_method) === "manual" ? "manual" : "auto",
          connection_ip: String(((_d = detail.config) == null ? void 0 : _d.connection_ip) || ""),
          profile_ids: detail.profile_ids || (detail.profiles || []).map((profile) => profile.id)
        });
      }
    }).finally(() => {
      setLoading(false);
      setDetailLoading(false);
    });
  }, [currentIsSmart, currentWorkAreaId, editConnection == null ? void 0 : editConnection.id, mode, open]);
  (0, import_react.useEffect)(() => {
    if (!open || !selectedWorkAreaId) return;
    setLoading(true);
    if (mode === "new") {
      setLoading(false);
      return;
    }
    (0, import_serve.getDevices)({
      workarea_id: selectedWorkAreaId,
      type_kind: targetKind,
      with: ["type", "model", "model.activeProfiles", "workarea"]
    }).then((list) => setDevices(list)).finally(() => setLoading(false));
  }, [mode, open, selectedWorkAreaId, targetKind]);
  const filteredDevices = (0, import_react.useMemo)(() => {
    const value = (0, import_constants.normalizeText)(keyword);
    return devices.filter(
      (device) => value ? (0, import_constants.normalizeText)(translation(device.name)).includes(value) : true
    );
  }, [devices, keyword, translation]);
  const resetConnectionConfig = () => {
    setEditFormValues(void 0);
  };
  const handlePickDevice = (device) => {
    if (connectedDeviceIds.includes(device.id)) return;
    if (pickingDeviceId) return;
    resetConnectionConfig();
    setPickingDeviceId(device.id);
    (0, import_serve.getDeviceDetail)(device.id).then((detail) => setSelectedDevice(detail || device)).catch(() => setSelectedDevice(device)).finally(() => {
      setPickingDeviceId(void 0);
      setStep("config");
    });
  };
  const handlePickModel = (model) => {
    resetConnectionConfig();
    setSelectedModel(model);
    setStep("config");
  };
  const handleBackToPick = () => {
    resetConnectionConfig();
    setSelectedDevice(void 0);
    setSelectedModel(void 0);
    setStep("pick");
  };
  const handleSubmit = (values) => {
    if (!smartDevice || !values.connection_type) return;
    const config = {
      connection_type: values.connection_type
    };
    if (needsNetworkConfig(values.connection_type)) {
      config.connection_method = values.connection_method || "auto";
      if (values.connection_method === "manual") {
        config.connection_ip = String(values.connection_ip || "").trim();
      }
    }
    const profileIds = values.profile_ids || [];
    if (mode === "edit") {
      if (!editConnection || !onUpdate) return;
      onUpdate(editConnection.id, {
        config,
        profile_ids: profileIds
      });
      return;
    }
    const payload = mode === "new" ? {
      type: "dumb",
      source_device_id: smartDevice.id,
      target_device_action: "new",
      target_device: {
        workarea_id: values.workarea_id || currentWorkAreaId || 0,
        model_code: (selectedModel == null ? void 0 : selectedModel.code) || "",
        name: values.name || { ...import_types.EMPTY_I18N }
      },
      config,
      profile_ids: profileIds
    } : {
      type: "dumb",
      source_device_id: smartDevice.id,
      target_device_id: peripheral == null ? void 0 : peripheral.id,
      target_device_action: "existing",
      config,
      profile_ids: profileIds
    };
    onSubmit == null ? void 0 : onSubmit(payload);
  };
  return {
    step,
    workAreas,
    brands,
    models,
    selectedWorkAreaId,
    selectedModel,
    keyword,
    editFormValues,
    loading,
    detailLoading,
    pickingDeviceId,
    currentIsSmart,
    targetKind,
    peripheral,
    smartDevice,
    profileOptions,
    profileRequired,
    filteredDevices,
    getWorkAreaDeviceCount,
    getDeviceCountText,
    setSelectedWorkAreaId,
    setKeyword,
    handlePickDevice,
    handlePickModel,
    handleBackToPick,
    handleSubmit
  };
};
// Annotate the CommonJS export names for ESM import in node:
0 && (module.exports = {
  useConnectDeviceModal
});
