import { _asyncToGenerator } from "../../../../../../_virtual/_@oxc-project_runtime@0.122.0/helpers/asyncToGenerator.js";
import { formatToken } from "../../../model/constants.js";
import { getConnectionTypeLabel } from "../../../shared/utils.js";
import ConnectExistingDeviceModal from "./ConnectExistingDeviceModal.js";
import ConnectionDeviceCard from "./ConnectionDeviceCard.js";
import ConnectedDevicePreviewModal from "./ConnectedDevicePreviewModal.js";
import React, { useState } from "react";
import { Dropdown, Empty, Spin } from "antd";
import { Button as Button$1, Icon, PisellModal } from "@pisell/materials";
import { DeleteOutlined, EditOutlined, LinkOutlined, PlusOutlined } from "@ant-design/icons";
import "./DeviceConnectionsPanel.less";
//#region src/plus/saasDevice/devicePlanning/modules/deviceConnections/components/DeviceConnectionsPanel.tsx
const DeviceConnectionsPanel = ({ activeKind, connectionType, isBuildIns, hideConnectButton, currentDevice, connections, loading, submitting, deleting, getText, translation, onCreateConnection, onUpdateConnection, onDeleteConnection }) => {
	const [removingConnection, setRemovingConnection] = useState();
	const [connectMode, setConnectMode] = useState();
	const [editingConnection, setEditingConnection] = useState();
	const [previewConnection, setPreviewConnection] = useState();
	if (activeKind === "integrated") return null;
	const isSmart = activeKind === "smart";
	const getConnectedDevice = (connection) => (isSmart ? connection.target_device : connection.source_device) || null;
	const getConnectedDeviceName = (connection) => {
		if (!connection) return "";
		const device = getConnectedDevice(connection);
		return device ? translation(device.name) || String(device.id) : "-";
	};
	const title = getText(isBuildIns ? "pisell2.saas.device-planning.drawer.build-ins" : isSmart ? "pisell2.saas.device-planning.drawer.connections.peripherals" : "pisell2.saas.device-planning.drawer.connections.connected-to");
	const emptyText = getText(isBuildIns ? "pisell2.saas.device-planning.drawer.build-ins.empty" : isSmart ? "pisell2.saas.device-planning.drawer.connections.no-peripherals" : "pisell2.saas.device-planning.drawer.connections.not-connected-smart");
	const menuItems = [{
		key: "connect-existing",
		icon: /* @__PURE__ */ React.createElement(LinkOutlined, null),
		label: getText("pisell2.saas.device-planning.drawer.connections.connect-existing"),
		onClick: () => setConnectMode("existing")
	}, {
		key: "add-new",
		icon: /* @__PURE__ */ React.createElement(PlusOutlined, null),
		label: getText("pisell2.saas.device-planning.drawer.connections.add-new"),
		onClick: () => setConnectMode("new")
	}];
	const actionItems = (connection) => [{
		key: "edit",
		icon: /* @__PURE__ */ React.createElement(EditOutlined, null),
		label: getText("pisell2.saas.device-planning.drawer.connections.edit-configuration"),
		onClick: () => setEditingConnection(connection)
	}, {
		key: "remove",
		icon: /* @__PURE__ */ React.createElement(DeleteOutlined, null),
		danger: true,
		label: getText("pisell2.saas.device-planning.drawer.connections.remove"),
		onClick: () => setRemovingConnection(connection)
	}];
	const connectButton = isBuildIns ? /* @__PURE__ */ React.createElement(Button$1, {
		icon: /* @__PURE__ */ React.createElement(PlusOutlined, null),
		onClick: () => setConnectMode("new")
	}, getText("pisell2.saas.device-planning.drawer.connections.connect")) : isSmart ? /* @__PURE__ */ React.createElement(Dropdown, {
		menu: { items: menuItems },
		trigger: ["click"],
		placement: "bottomRight"
	}, /* @__PURE__ */ React.createElement(Button$1, { icon: /* @__PURE__ */ React.createElement(PlusOutlined, null) }, getText("pisell2.saas.device-planning.drawer.connections.connect"))) : /* @__PURE__ */ React.createElement(Button$1, {
		icon: /* @__PURE__ */ React.createElement(PlusOutlined, null),
		onClick: () => setConnectMode("existing")
	}, getText("pisell2.saas.device-planning.drawer.connections.connect"));
	const getStatusLabel = (value) => {
		if (!value) return "-";
		const key = `pisell2.saas.device-planning.status.${value}`;
		const text = getText(key);
		return text && text !== key ? text : value;
	};
	const getStatusTone = (value) => {
		if (value === "online" || value === "connected" || value === "linked") return "success";
		if (value === "connecting") return "processing";
		if (value === "unlinked") return "warning";
		if (value === "disconnected") return "error";
		return "default";
	};
	const getDataValue = (data, key) => {
		if (!data) return void 0;
		const value = data[key];
		if (value == null || typeof value === "object") return void 0;
		return String(value);
	};
	const getNetworkLocalIp = (data) => {
		const network = data === null || data === void 0 ? void 0 : data.network;
		if (!network || typeof network !== "object" || Array.isArray(network)) return;
		return getDataValue(network, "local_ip");
	};
	const getConnectionLines = (connection) => {
		var _connection$config;
		const connectionType = getConnectionTypeLabel((_connection$config = connection.config) === null || _connection$config === void 0 ? void 0 : _connection$config.connection_type);
		const parts = [connectionType === "-" ? void 0 : connectionType];
		const connectionData = connection.data;
		const ip = getDataValue(connectionData, "ip") || getNetworkLocalIp(connectionData);
		const port = getDataValue(connectionData, "port");
		const macAddress = getDataValue(connectionData, "mac");
		if (ip) parts.push(`IP: ${ip}`);
		if (port) parts.push(`Port: ${port}`);
		if (macAddress) parts.push(`MAC: ${macAddress}`);
		return parts.filter(Boolean).length ? [parts.filter(Boolean).join(" · ")] : [];
	};
	const getDeviceStatusLines = (device) => {
		var _device$data, _device$data2;
		if ((device === null || device === void 0 ? void 0 : device.type_kind) !== "smart") return [];
		const ip = ((_device$data = device.data) === null || _device$data === void 0 ? void 0 : _device$data.ip) || (device === null || device === void 0 || (_device$data2 = device.data) === null || _device$data2 === void 0 || (_device$data2 = _device$data2.network) === null || _device$data2 === void 0 ? void 0 : _device$data2.local_ip);
		return ip ? [`IP: ${ip}`] : [];
	};
	const getDeviceStatuses = (device) => {
		if ((device === null || device === void 0 ? void 0 : device.type_kind) === "smart") return [{
			key: "link",
			label: getStatusLabel(device.link || "unconnected"),
			tone: getStatusTone(device.link || "unconnected")
		}, {
			key: "online",
			label: getStatusLabel(device.status || "unknown"),
			tone: getStatusTone(device.status || "unknown")
		}];
		return [{
			key: "online",
			label: getStatusLabel((device === null || device === void 0 ? void 0 : device.status) || "unknown"),
			tone: getStatusTone((device === null || device === void 0 ? void 0 : device.status) || "unknown")
		}];
	};
	const renderConnectionItem = (connection) => {
		var _device$type, _device$model, _device$model2, _device$model3, _device$type2;
		const device = getConnectedDevice(connection);
		return /* @__PURE__ */ React.createElement(ConnectionDeviceCard, {
			key: connection.id,
			title: device ? translation(device.name) || device.id : "-",
			deviceInfo: {
				icon: (device === null || device === void 0 || (_device$type = device.type) === null || _device$type === void 0 ? void 0 : _device$type.icon) || (isSmart ? "PrinterOutlined" : "DesktopOutlined"),
				modelName: translation(device === null || device === void 0 || (_device$model = device.model) === null || _device$model === void 0 ? void 0 : _device$model.name) || (device === null || device === void 0 ? void 0 : device.model_code) || "-",
				brandName: translation(device === null || device === void 0 || (_device$model2 = device.model) === null || _device$model2 === void 0 || (_device$model2 = _device$model2.brand) === null || _device$model2 === void 0 ? void 0 : _device$model2.name) || (device === null || device === void 0 || (_device$model3 = device.model) === null || _device$model3 === void 0 ? void 0 : _device$model3.brand_code) || "-",
				typeName: translation(device === null || device === void 0 || (_device$type2 = device.type) === null || _device$type2 === void 0 ? void 0 : _device$type2.name) || (device === null || device === void 0 ? void 0 : device.type_code) || "-",
				statusLines: getDeviceStatusLines(device)
			},
			connectionInfo: { lines: getConnectionLines(connection) },
			deviceStatuses: getDeviceStatuses(device),
			connectionStatuses: [{
				key: "connection",
				label: getStatusLabel(connection.status || "unconnected"),
				tone: getStatusTone(connection.status || "unconnected")
			}],
			profiles: (connection.profiles || []).map((profile) => ({
				key: String(profile.id),
				label: translation(profile.name) || profile.id
			})),
			lastSeen: connection.last_seen ? `${getText("pisell2.saas.device-planning.detail.last-seen")}${connection.last_seen}` : void 0,
			actions: actionItems(connection),
			showPreview: isSmart,
			onPreview: () => setPreviewConnection(connection)
		});
	};
	return /* @__PURE__ */ React.createElement("div", { className: "device-detail-drawer__connections" }, /* @__PURE__ */ React.createElement("div", { className: "device-detail-drawer__connections-header" }, /* @__PURE__ */ React.createElement("div", { className: "device-detail-drawer__connections-title" }, /* @__PURE__ */ React.createElement(Icon, { type: isSmart ? "ApiOutlined" : "LinkOutlined" }), /* @__PURE__ */ React.createElement("span", null, title)), hideConnectButton ? null : connectButton), /* @__PURE__ */ React.createElement(Spin, { spinning: loading }, connections.length ? /* @__PURE__ */ React.createElement("div", { className: "device-detail-drawer__connection-list" }, connections.map(renderConnectionItem)) : /* @__PURE__ */ React.createElement("div", { className: "device-detail-drawer__connections-empty" }, /* @__PURE__ */ React.createElement(Empty, {
		image: Empty.PRESENTED_IMAGE_SIMPLE,
		description: emptyText
	}))), removingConnection ? /* @__PURE__ */ React.createElement(PisellModal, {
		open: true,
		title: getText("pisell2.saas.device-planning.drawer.connections.remove-title"),
		onCancel: () => setRemovingConnection(void 0),
		okText: getText("pisell2.saas.device-planning.drawer.connections.remove"),
		cancelText: getText("pisell2.saas.device-planning.drawer.connections.cancel"),
		okButtonProps: {
			block: true,
			size: "large",
			danger: true,
			loading: deleting,
			onClick: function() {
				var _ref = _asyncToGenerator(function* () {
					yield onDeleteConnection(removingConnection.id);
					setRemovingConnection(void 0);
				});
				return function onClick() {
					return _ref.apply(this, arguments);
				};
			}()
		},
		cancelButtonProps: {
			block: true,
			size: "large",
			type: "default",
			disabled: deleting,
			onClick: () => setRemovingConnection(void 0)
		},
		width: 460,
		headerDivider: false
	}, formatToken(getText("pisell2.saas.device-planning.drawer.connections.remove-confirm"), { DeviceName: getConnectedDeviceName(removingConnection) })) : null, connectMode ? /* @__PURE__ */ React.createElement(ConnectExistingDeviceModal, {
		open: true,
		mode: connectMode,
		connectionType,
		targetStructure: isBuildIns ? "component" : void 0,
		currentDevice,
		connectedDeviceIds: connections.map((connection) => activeKind === "smart" ? connection.target_device_id : connection.source_device_id),
		currentWorkAreaId: currentDevice.workarea_id,
		getText,
		translation,
		submitting,
		onClose: () => setConnectMode(void 0),
		onSubmit: function() {
			var _ref2 = _asyncToGenerator(function* (payload) {
				yield onCreateConnection(payload);
				setConnectMode(void 0);
			});
			return function(_x) {
				return _ref2.apply(this, arguments);
			};
		}()
	}) : null, editingConnection ? /* @__PURE__ */ React.createElement(ConnectExistingDeviceModal, {
		open: true,
		mode: "edit",
		connectionType,
		currentDevice,
		editConnection: editingConnection,
		connectedDeviceIds: [],
		currentWorkAreaId: currentDevice.workarea_id,
		getText,
		translation,
		submitting,
		onClose: () => setEditingConnection(void 0),
		onUpdate: function() {
			var _ref3 = _asyncToGenerator(function* (id, payload) {
				yield onUpdateConnection(id, payload);
				setEditingConnection(void 0);
			});
			return function(_x2, _x3) {
				return _ref3.apply(this, arguments);
			};
		}()
	}) : null, (previewConnection === null || previewConnection === void 0 ? void 0 : previewConnection.target_device) ? /* @__PURE__ */ React.createElement(ConnectedDevicePreviewModal, {
		open: true,
		device: previewConnection.target_device,
		connectionType,
		getText,
		translation,
		onClose: () => setPreviewConnection(void 0)
	}) : null);
};
//#endregion
export { DeviceConnectionsPanel as default };
