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 useEngineContext from "../../hooks/useEngineContext.js";
import useComponents from "../../hooks/useComponents.js";
import ImageUpload from "./components/ImageUpload/index.js";
import JsonEditor from "./components/JsonEditor/index.js";
import locales_default from "./locales.js";
import SortableWalletPassTypes, { DEFAULT_WALLET_PASS_TYPES_CONFIG } from "./components/sortableWalletPassTypes/index.js";
import ValidityPeriodSelector from "./components/ValidityPeriodSelector/index.js";
import RelationProduct from "./components/relationProduct/index.js";
import React, { forwardRef, useCallback, useEffect, useImperativeHandle, useMemo, useRef, useState } from "react";
import { Form, InputNumber, Radio } from "antd";
import { locales } from "@pisell/utils";
import { Icon, PisellModal, Translation, WalletCard } from "@pisell/materials";
import "./WalletEditor.less";
//#region src/plus/walletEditor/WalletEditor.tsx
const WalletEditor = forwardRef((props, ref) => {
	var _context$appHelper$ut, _context$appHelper$ut2, _context$appHelper$ut3, _context$appHelper$ut4, _context$appHelper$ut5, _context$appHelper$ut6, _store$global;
	const { value, onChange, disabled = false, className, style } = props;
	const context = useEngineContext();
	locales.init(locales_default, ((_context$appHelper$ut = context.appHelper.utils) === null || _context$appHelper$ut === void 0 || (_context$appHelper$ut = _context$appHelper$ut.storage) === null || _context$appHelper$ut === void 0 ? void 0 : _context$appHelper$ut.get("umi_locale")) || "en");
	const amountSymbol = ((_context$appHelper$ut2 = (_context$appHelper$ut3 = context.appHelper.utils).getData) === null || _context$appHelper$ut2 === void 0 ? void 0 : _context$appHelper$ut2.call(_context$appHelper$ut3, "shop_symbol")) || "";
	const shopName = ((_store$global = (((_context$appHelper$ut4 = (_context$appHelper$ut5 = context.appHelper.utils).getStore) === null || _context$appHelper$ut4 === void 0 || (_context$appHelper$ut4 = _context$appHelper$ut4.call(_context$appHelper$ut5)) === null || _context$appHelper$ut4 === void 0 || (_context$appHelper$ut6 = _context$appHelper$ut4.getState) === null || _context$appHelper$ut6 === void 0 ? void 0 : _context$appHelper$ut6.call(_context$appHelper$ut4)) || {}).global) === null || _store$global === void 0 || (_store$global = _store$global.shopDetail) === null || _store$global === void 0 ? void 0 : _store$global.name) || "";
	const [sendConfigVisible, setSendConfigVisible] = useState(true);
	const [previewVisible, setPreviewVisible] = useState(false);
	const [form] = Form.useForm();
	const isControlled = value !== void 0;
	const [HolderSelector] = useComponents({ components: ["HolderSelector"] });
	const holderSelectorRef = useRef(null);
	const defaultValue = useMemo(() => ({
		status: "enable",
		valid_for: {
			unit: "1",
			unit_type: "year",
			type: "normal"
		},
		metadata: {
			holder: { type: "customer" },
			showcaseWalletPassNew: DEFAULT_WALLET_PASS_TYPES_CONFIG.map((item) => _objectSpread2(_objectSpread2({}, item), {}, { display: 1 })),
			coverImage: "",
			send_config: { type: "register" }
		}
	}), []);
	const currentValue = useMemo(() => {
		return _objectSpread2(_objectSpread2({}, defaultValue), value);
	}, [value, defaultValue]);
	useImperativeHandle(ref, () => ({
		form,
		setInitialValues: (values) => {
			form.setFieldsValue(_objectSpread2(_objectSpread2({}, defaultValue), values));
		},
		getValues: () => {
			var _formValues$metadata;
			const formValues = form.getFieldsValue();
			return _objectSpread2(_objectSpread2({}, formValues), {}, { metadata: _objectSpread2(_objectSpread2({}, formValues.metadata), {}, { showcaseWalletPass: convertShowcaseWalletPass((_formValues$metadata = formValues.metadata) === null || _formValues$metadata === void 0 ? void 0 : _formValues$metadata.showcaseWalletPassNew) }) });
		}
	}), [form, defaultValue]);
	useEffect(() => {
		if (isControlled && currentValue) form.setFieldsValue(currentValue);
	}, [
		currentValue,
		form,
		isControlled
	]);
	const convertShowcaseWalletPass = (showcaseWalletPassNew) => {
		if (!showcaseWalletPassNew) return [];
		return showcaseWalletPassNew.filter((item) => item.display === 1).map((item) => item.type);
	};
	const toggleSendConfig = useCallback(() => {
		setSendConfigVisible((prev) => !prev);
	}, []);
	return /* @__PURE__ */ React.createElement(React.Fragment, null, /* @__PURE__ */ React.createElement("div", {
		className: `wallet-editor ${className || ""}`,
		style
	}, /* @__PURE__ */ React.createElement(Form, {
		size: "large",
		form,
		layout: "vertical",
		initialValues: isControlled ? currentValue : _objectSpread2({}, defaultValue),
		onValuesChange: (...args) => {
			var _props$onValuesChange;
			(_props$onValuesChange = props.onValuesChange) === null || _props$onValuesChange === void 0 || _props$onValuesChange.call(props, ...args);
		},
		onFinish: (values) => {
			if (onChange) {
				var _values$metadata;
				onChange(_objectSpread2(_objectSpread2({}, values), {}, { metadata: _objectSpread2(_objectSpread2({}, values.metadata), {}, { showcaseWalletPass: convertShowcaseWalletPass((_values$metadata = values.metadata) === null || _values$metadata === void 0 ? void 0 : _values$metadata.showcaseWalletPassNew) }) }));
			}
		},
		disabled
	}, /* @__PURE__ */ React.createElement("div", { style: {
		padding: "20px 20px 0px 20px",
		borderRadius: 10,
		marginTop: 24,
		border: "1px solid var(--Gray-300,#d0d5dd)"
	} }, /* @__PURE__ */ React.createElement(Form.Item, {
		label: locales.getText("walletName"),
		name: "name",
		rules: [{ validator: function() {
			var _ref = _asyncToGenerator(function* (_, value) {
				const msg = locales.getText("pleaseInputWalletName");
				if (value == null || typeof value !== "object") return Promise.reject(new Error(msg));
				const keys = Object.keys(value);
				if (keys.length === 0) return Promise.reject(new Error(msg));
				return keys.some((k) => {
					const v = value[k];
					return typeof v === "string" && v.trim() !== "";
				}) ? Promise.resolve() : Promise.reject(new Error(msg));
			});
			return function validator(_x, _x2) {
				return _ref.apply(this, arguments);
			};
		}() }]
	}, /* @__PURE__ */ React.createElement(Translation, null)), /* @__PURE__ */ React.createElement(Form.Item, {
		label: locales.getText("validityPeriod"),
		name: "valid_for"
	}, /* @__PURE__ */ React.createElement(ValidityPeriodSelector, null)), /* @__PURE__ */ React.createElement(Form.Item, {
		label: locales.getText("linkedPasses"),
		name: "relation_id",
		initialValue: []
	}, /* @__PURE__ */ React.createElement(RelationProduct, null)), HolderSelector && /* @__PURE__ */ React.createElement(Form.Item, {
		label: locales.getText("pisell2.wallet-editor.holder"),
		name: ["metadata", "holder"],
		initialValue: { type: "customer" },
		rules: [{ validator: function() {
			var _ref2 = _asyncToGenerator(function* (_, value) {
				if ((value === null || value === void 0 ? void 0 : value.type) === "custom") {
					var _value$custom, _holderSelectorRef$cu, _holderSelectorRef$cu2;
					if (!(value === null || value === void 0 || (_value$custom = value.custom) === null || _value$custom === void 0 ? void 0 : _value$custom.custom_id)) return Promise.reject(new Error(locales.getText("pisell2.wallet-editor.holder.required")));
					const options = ((_holderSelectorRef$cu = holderSelectorRef.current) === null || _holderSelectorRef$cu === void 0 || (_holderSelectorRef$cu2 = _holderSelectorRef$cu.getOptions) === null || _holderSelectorRef$cu2 === void 0 ? void 0 : _holderSelectorRef$cu2.call(_holderSelectorRef$cu)) || [];
					if (!(options === null || options === void 0 ? void 0 : options.find((item) => {
						var _value$custom2;
						return item.value === (value === null || value === void 0 || (_value$custom2 = value.custom) === null || _value$custom2 === void 0 ? void 0 : _value$custom2.custom_id);
					}))) return Promise.reject(new Error(locales.getText("pisell2.wallet-editor.holder.invalid")));
				}
				return Promise.resolve();
			});
			return function validator(_x3, _x4) {
				return _ref2.apply(this, arguments);
			};
		}() }]
	}, /* @__PURE__ */ React.createElement(HolderSelector, { ref: holderSelectorRef })), /* @__PURE__ */ React.createElement(Form.Item, {
		label: locales.getText("sort"),
		name: "sort"
	}, /* @__PURE__ */ React.createElement(InputNumber, { style: { width: "100%" } })), /* @__PURE__ */ React.createElement(Form.Item, {
		label: locales.getText("status"),
		name: "status",
		initialValue: "enable"
	}, /* @__PURE__ */ React.createElement(Radio.Group, null, /* @__PURE__ */ React.createElement(Radio, { value: "enable" }, locales.getText("enable")), /* @__PURE__ */ React.createElement(Radio, { value: "disable" }, locales.getText("disable")))), /* @__PURE__ */ React.createElement(Form.Item, { label: locales.getText("distributionConditions") }, /* @__PURE__ */ React.createElement("div", {
		style: {
			color: "#8c5cff",
			cursor: "pointer",
			height: 40,
			display: "flex",
			alignItems: "center",
			border: "none",
			background: "transparent",
			padding: 0
		},
		onClick: toggleSendConfig
	}, locales.getText("advancedSettings"), " ", /* @__PURE__ */ React.createElement(Icon, {
		type: "pisell2-chevron-down",
		size: 18,
		style: { transform: sendConfigVisible ? "rotate(0deg)" : "rotate(180deg)" }
	})), /* @__PURE__ */ React.createElement(Form.Item, {
		noStyle: true,
		name: ["metadata", "send_config"],
		initialValue: { type: "register" }
	}, /* @__PURE__ */ React.createElement(JsonEditor, {
		placeholder: locales.getText("enterJSONConfig"),
		rows: 4,
		disabled,
		style: { display: sendConfigVisible ? "block" : "none" }
	})))), /* @__PURE__ */ React.createElement("div", { style: {
		padding: "20px 20px 0px 20px",
		borderRadius: 10,
		margin: "24px 0",
		border: "1px solid var(--Gray-300,#d0d5dd)"
	} }, /* @__PURE__ */ React.createElement("div", { style: {
		marginBottom: "8px",
		display: "flex",
		justifyContent: "space-between",
		alignItems: "center"
	} }, /* @__PURE__ */ React.createElement("span", { style: {
		fontWeight: "bold",
		fontSize: 16
	} }, locales.getText("displaySettings")), /* @__PURE__ */ React.createElement("span", {
		style: {
			color: "#8c5cff",
			cursor: "pointer"
		},
		onClick: () => setPreviewVisible(true)
	}, locales.getText("viewPreview"))), /* @__PURE__ */ React.createElement(Form.Item, {
		label: "",
		name: ["metadata", "showcaseWalletPassNew"],
		initialValue: DEFAULT_WALLET_PASS_TYPES_CONFIG.map((item) => _objectSpread2(_objectSpread2({}, item), {}, { display: 1 }))
	}, /* @__PURE__ */ React.createElement(SortableWalletPassTypes, null)), /* @__PURE__ */ React.createElement(Form.Item, {
		label: locales.getText("icon"),
		name: ["metadata", "icon"]
	}, /* @__PURE__ */ React.createElement(ImageUpload, null)), /* @__PURE__ */ React.createElement(Form.Item, {
		label: locales.getText("coverImage"),
		name: ["metadata", "coverImage"]
	}, /* @__PURE__ */ React.createElement(ImageUpload, null))))), /* @__PURE__ */ React.createElement(PisellModal, {
		open: previewVisible,
		onCancel: () => setPreviewVisible(false),
		title: locales.getText("preview"),
		width: "auto",
		footer: false,
		header: false,
		className: "pisell-wallet-editor_preview-modal"
	}, /* @__PURE__ */ React.createElement(WalletCard, {
		mode: "dark",
		shopName,
		cardStyle: "normal",
		codeType: "qrCode",
		symbol: amountSymbol,
		items: form.getFieldValue(["metadata", "showcaseWalletPassNew"]),
		customBackgroundImage: form.getFieldValue(["metadata", "coverImage"]),
		iconImg: form.getFieldValue(["metadata", "icon"]),
		style: { minWidth: 368 }
	})));
});
//#endregion
export { WalletEditor as default };
