import { _objectSpread2 } from "../../../../_virtual/_@oxc-project_runtime@0.122.0/helpers/objectSpread2.js";
import { getDeviceBrands, getDeviceConnectionDetail, getDeviceDetail, getDeviceTypes, getDevices, getWorkAreas } from "../serve.js";
import { normalizeText } from "../constants.js";
import { flattenDeviceModels, isProfileRequired } from "../utils.js";
import { EMPTY_I18N } from "../types.js";
import { useEffect, useMemo, useState } from "react";
//#region src/plus/saasDevice/appPeripheral/hooks/useConnectDeviceModal.ts
const needsNetworkConfig = (connectionType) => connectionType === "ethernet" || connectionType === "wifi";
const useConnectDeviceModal = ({ open, mode, currentDevice, editConnection, connectedDeviceIds, currentWorkAreaId, getText, translation, onSubmit, onUpdate }) => {
	const [step, setStep] = useState("pick");
	const [workAreas, setWorkAreas] = useState([]);
	const [selectedWorkAreaId, setSelectedWorkAreaId] = useState();
	const [devices, setDevices] = useState([]);
	const [models, setModels] = useState([]);
	const [brands, setBrands] = useState([]);
	const [selectedDevice, setSelectedDevice] = useState();
	const [selectedModel, setSelectedModel] = useState();
	const [keyword, setKeyword] = useState("");
	const [editFormValues, setEditFormValues] = useState();
	const [loading, setLoading] = useState(false);
	const [detailLoading, setDetailLoading] = useState(false);
	const [pickingDeviceId, setPickingDeviceId] = 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 || peripheral === void 0 ? void 0 : peripheral.model_code) ? models.find((model) => model.code === peripheral.model_code) : void 0;
	const profileSource = mode === "new" ? selectedModel : (peripheral === null || peripheral === void 0 ? void 0 : peripheral.model) || fallbackProfileModel;
	const profileOptions = ((profileSource === null || profileSource === void 0 ? void 0 : profileSource.active_profiles) || []).map((profile) => ({
		label: translation(profile.name) || String(profile.id),
		value: profile.id
	}));
	const profileRequired = isProfileRequired(profileSource);
	const getWorkAreaDeviceCount = (area) => targetKind === "smart" ? area.smart_devices_count || 0 : area.dumb_devices_count || 0;
	const getDeviceCountText = (count) => {
		return getText(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").replace("{N}", String(count));
	};
	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([
			getWorkAreas(),
			mode === "new" ? getDeviceBrands() : Promise.resolve([]),
			getDeviceTypes({
				kind: "dumb",
				with: [
					"activeModels",
					"activeModels.activeProfiles",
					"activeModels.brand"
				]
			}),
			mode === "edit" && (editConnection === null || editConnection === void 0 ? void 0 : editConnection.id) ? getDeviceConnectionDetail(editConnection.id) : Promise.resolve(null)
		]).then(([areas, brandList, types, detail]) => {
			var _areas$;
			setWorkAreas(areas);
			setBrands(brandList);
			setModels(flattenDeviceModels(types));
			setSelectedWorkAreaId(currentWorkAreaId || ((_areas$ = areas[0]) === null || _areas$ === void 0 ? void 0 : _areas$.id));
			if (detail) {
				var _detail$config, _detail$config2, _detail$config3;
				setSelectedDevice(currentIsSmart ? detail.target_device || void 0 : detail.source_device || void 0);
				setEditFormValues({
					connection_type: (_detail$config = detail.config) === null || _detail$config === void 0 ? void 0 : _detail$config.connection_type,
					connection_method: ((_detail$config2 = detail.config) === null || _detail$config2 === void 0 ? void 0 : _detail$config2.connection_method) === "manual" ? "manual" : "auto",
					connection_ip: String(((_detail$config3 = detail.config) === null || _detail$config3 === void 0 ? void 0 : _detail$config3.connection_ip) || ""),
					profile_ids: detail.profile_ids || (detail.profiles || []).map((profile) => profile.id)
				});
			}
		}).finally(() => {
			setLoading(false);
			setDetailLoading(false);
		});
	}, [
		currentIsSmart,
		currentWorkAreaId,
		editConnection === null || editConnection === void 0 ? void 0 : editConnection.id,
		mode,
		open
	]);
	useEffect(() => {
		if (!open || !selectedWorkAreaId) return;
		setLoading(true);
		if (mode === "new") {
			setLoading(false);
			return;
		}
		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 = useMemo(() => {
		const value = normalizeText(keyword);
		return devices.filter((device) => value ? 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);
		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 || selectedModel === void 0 ? void 0 : selectedModel.code) || "",
				name: values.name || _objectSpread2({}, EMPTY_I18N)
			},
			config,
			profile_ids: profileIds
		} : {
			type: "dumb",
			source_device_id: smartDevice.id,
			target_device_id: peripheral === null || peripheral === void 0 ? void 0 : peripheral.id,
			target_device_action: "existing",
			config,
			profile_ids: profileIds
		};
		onSubmit === null || onSubmit === 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
	};
};
//#endregion
export { useConnectDeviceModal };
