import { _objectSpread2 } from "../../../../../_virtual/_@oxc-project_runtime@0.122.0/helpers/objectSpread2.js";
import { _asyncToGenerator } from "../../../../../_virtual/_@oxc-project_runtime@0.122.0/helpers/asyncToGenerator.js";
import { DEVICE_KIND_LABEL_KEY, normalizeText } from "../../constants.js";
import { EMPTY_I18N, validateI18nRequired } from "../../types.js";
import React, { useEffect, useMemo, useState } from "react";
import { Form } from "antd";
import { BaseTranslation, Button as Button$1, Empty as Empty$1, Icon, Input as Input$1, PisellModal, Select as Select$1 } from "@pisell/materials";
import classNames from "classnames";
import { ArrowLeftOutlined, SearchOutlined } from "@ant-design/icons";
import "./index.less";
//#region src/plus/saasDevice/devicePlanning/components/AddDeviceModal/index.tsx
const isProfileRequired = (model) => {
	var _model$data;
	return Boolean(model === null || model === void 0 || (_model$data = model.data) === null || _model$data === void 0 || (_model$data = _model$data.profile_structure) === null || _model$data === void 0 ? void 0 : _model$data.required);
};
const hasI18nValue = (value) => {
	if (!value) return false;
	return Object.values(value).some((item) => String(item || "").trim());
};
const AddDeviceModal = ({ open, activeKind, models, workAreaId, submitting, getText, translation, onClose, onSubmit }) => {
	const [form] = Form.useForm();
	const [step, setStep] = useState("model");
	const [keyword, setKeyword] = useState("");
	const [selectedModel, setSelectedModel] = useState();
	const nameValue = Form.useWatch("name", form);
	const profileValue = Form.useWatch("profile_id", form);
	useEffect(() => {
		if (!open) return;
		setStep("model");
		setKeyword("");
		setSelectedModel(void 0);
		form.resetFields();
		form.setFieldsValue({ name: _objectSpread2({}, EMPTY_I18N) });
	}, [form, open]);
	const filteredModels = useMemo(() => {
		const value = normalizeText(keyword);
		if (!value) return models;
		return models.filter((model) => {
			return [
				translation(model.name),
				translation(model.description),
				model.code,
				model.type_code
			].some((item) => normalizeText(item || "").includes(value));
		});
	}, [
		keyword,
		models,
		translation
	]);
	const groupedModels = useMemo(() => {
		const groups = /* @__PURE__ */ new Map();
		filteredModels.forEach((model) => {
			const key = model.type_code || getText(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 || selectedModel === void 0 ? 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: _objectSpread2({}, EMPTY_I18N),
			profile_id: void 0
		});
	};
	const handleSave = function() {
		var _ref = _asyncToGenerator(function* () {
			if (!canSave || !selectedModel || !workAreaId) return;
			const values = yield form.validateFields();
			onSubmit({
				workarea_id: workAreaId,
				model_code: selectedModel.code,
				profile_id: profileRequired ? values.profile_id || null : null,
				name: values.name
			});
		});
		return function handleSave() {
			return _ref.apply(this, arguments);
		};
	}();
	const renderModelStep = () => /* @__PURE__ */ React.createElement("div", { className: "add-device-modal__body" }, /* @__PURE__ */ React.createElement(Input$1, {
		allowClear: true,
		prefix: /* @__PURE__ */ React.createElement(SearchOutlined, null),
		value: keyword,
		placeholder: getText("pisell2.saas.device-planning.add.search"),
		onChange: (event) => setKeyword(event.target.value)
	}), /* @__PURE__ */ React.createElement("div", { className: "add-device-modal__model-list" }, groupedModels.length ? groupedModels.map(([typeCode, items]) => {
		var _items$;
		const type = (_items$ = items[0]) === null || _items$ === void 0 ? void 0 : _items$.type;
		const typeName = translation(type === null || type === void 0 ? void 0 : type.name) || typeCode;
		return /* @__PURE__ */ React.createElement("div", {
			key: typeCode,
			className: "add-device-modal__model-group"
		}, /* @__PURE__ */ React.createElement("div", { className: "add-device-modal__group-title" }, (type === null || type === void 0 ? void 0 : type.icon) ? /* @__PURE__ */ React.createElement(Icon, { type: type === null || type === void 0 ? void 0 : type.icon }) : null, /* @__PURE__ */ React.createElement("span", null, typeName)), /* @__PURE__ */ React.createElement("div", { className: "add-device-modal__model-grid" }, items.map((model) => /* @__PURE__ */ React.createElement("div", {
			key: model.code,
			className: classNames("add-device-modal__model-card", { "is-selected": (selectedModel === null || selectedModel === void 0 ? void 0 : selectedModel.code) === model.code }),
			onClick: () => handleSelectModel(model)
		}, /* @__PURE__ */ React.createElement("div", { className: "add-device-modal__model-name" }, translation(model.name) || ""), /* @__PURE__ */ React.createElement("div", { className: "add-device-modal__model-desc" }, translation(model.description) || "")))));
	}) : /* @__PURE__ */ React.createElement(Empty$1, {
		image: Empty$1.PRESENTED_IMAGE_SIMPLE,
		description: /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("div", null, getText("pisell2.saas.device-planning.add.no-devices")), /* @__PURE__ */ React.createElement("div", null, getText("pisell2.saas.device-planning.add.adjust-search")))
	})));
	const renderConfigureStep = () => {
		var _selectedModel$type;
		return /* @__PURE__ */ React.createElement("div", { className: "add-device-modal__body" }, selectedModel ? /* @__PURE__ */ React.createElement("div", { className: "add-device-modal__selected-model" }, /* @__PURE__ */ React.createElement(Icon, { type: ((_selectedModel$type = selectedModel.type) === null || _selectedModel$type === void 0 ? void 0 : _selectedModel$type.icon) || "DesktopOutlined" }), /* @__PURE__ */ React.createElement("div", null, /* @__PURE__ */ React.createElement("div", { className: "add-device-modal__model-name" }, translation(selectedModel.name) || ""), /* @__PURE__ */ React.createElement("div", { className: "add-device-modal__model-desc" }, translation(selectedModel.description) || ""))) : null, /* @__PURE__ */ React.createElement(Form, {
			form,
			layout: "vertical",
			preserve: false
		}, /* @__PURE__ */ React.createElement(Form.Item, {
			name: "name",
			label: getText("pisell2.saas.device-planning.add.device-name"),
			required: true,
			rules: [{ validator: validateI18nRequired(getText("pisell2.saas.device-planning.add.device-name-required")) }]
		}, /* @__PURE__ */ React.createElement(BaseTranslation, { renderMode: "edit" })), profileRequired ? /* @__PURE__ */ React.createElement(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__ */ React.createElement(Select$1, {
			disabled: profiles.length === 0,
			options: profiles.map((profile) => ({
				label: translation(profile.name) || String(profile.id),
				value: profile.id
			}))
		})) : null));
	};
	return /* @__PURE__ */ React.createElement(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__ */ React.createElement(Button$1, {
		type: "text",
		icon: /* @__PURE__ */ React.createElement(ArrowLeftOutlined, null),
		className: "add-device-modal__back-icon",
		onClick: () => setStep("model")
	}) : null, step === "model" ? renderModelStep() : renderConfigureStep(), /* @__PURE__ */ React.createElement("div", { className: "add-device-modal__footer" }, step === "model" ? /* @__PURE__ */ React.createElement(Button$1, {
		type: "text",
		onClick: onClose
	}, getText("pisell2.saas.device-planning.add.cancel")) : /* @__PURE__ */ React.createElement(React.Fragment, null, /* @__PURE__ */ React.createElement(Button$1, {
		type: "text",
		onClick: () => setStep("model")
	}, getText("pisell2.saas.device-planning.add.back")), /* @__PURE__ */ React.createElement(Button$1, {
		type: "primary",
		disabled: !canSave,
		loading: submitting,
		onClick: handleSave
	}, getText("pisell2.saas.device-planning.add.save")))));
};
//#endregion
export { AddDeviceModal as default };
