import { _asyncToGenerator } from "../../../../_virtual/_@oxc-project_runtime@0.122.0/helpers/asyncToGenerator.js";
import useEngineContext from "../../../../hooks/useEngineContext.js";
import CashKeyboard from "../../../../pro/priceKeyboard/components/cashKeyboard/index.js";
import useToast from "../../../../hooks/useToast.js";
import locales_default from "../../locales.js";
import React, { useEffect, useMemo, useState } from "react";
import { formatAmount, locales } from "@pisell/utils";
import { useDebounceFn } from "ahooks";
import "./index.less";
//#region src/components/checkout/components/CashPaymentModule/index.tsx
function CashPaymentModule({ amountSymbol, orderInfo, onPaymentComplete, customAmount, amountButtons = [], disabled = false, roundingFunction, balanceDueAmount = "0", balanceDueTotalAmount = "0", syncingLock = false, shortcutsSize = "default" }) {
	const [amount, setAmount] = useState(customAmount || "");
	const [roundingAmount, setRoundingAmount] = useState(0);
	const [roundingBaseInfo, setRoundingBaseInfo] = useState({
		orderBaseAmount: 0,
		roundedBaseAmount: 0,
		orderRoundingAmount: 0
	});
	const context = useEngineContext();
	const Toast = useToast();
	const getText = (key, fallback) => {
		var _context$appHelper, _context$appHelper$ge, _context$appHelper$ge2, _context$appHelper$ut, _currentLang;
		const currentLang = ((_context$appHelper = context.appHelper) === null || _context$appHelper === void 0 || (_context$appHelper = _context$appHelper.utils) === null || _context$appHelper === void 0 || (_context$appHelper$ge = _context$appHelper.getApp) === null || _context$appHelper$ge === void 0 || (_context$appHelper$ge = _context$appHelper$ge.call(_context$appHelper)) === null || _context$appHelper$ge === void 0 || (_context$appHelper$ge = _context$appHelper$ge.locales) === null || _context$appHelper$ge === void 0 || (_context$appHelper$ge2 = _context$appHelper$ge.getLocale) === null || _context$appHelper$ge2 === void 0 ? void 0 : _context$appHelper$ge2.call(_context$appHelper$ge)) || ((_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 checkoutText = locales_default === null || locales_default === void 0 || (_currentLang = locales_default[currentLang]) === null || _currentLang === void 0 ? void 0 : _currentLang[key];
		if (checkoutText) return checkoutText;
		return locales.getText(key) || fallback;
	};
	const orderBaseAmount = useMemo(() => {
		const baseAmount = parseFloat((orderInfo === null || orderInfo === void 0 ? void 0 : orderInfo.isDeposit) ? balanceDueTotalAmount || "0" : balanceDueAmount || "0");
		return Number.isFinite(baseAmount) ? baseAmount : 0;
	}, [
		orderInfo === null || orderInfo === void 0 ? void 0 : orderInfo.isDeposit,
		balanceDueAmount,
		balanceDueTotalAmount
	]);
	const isAmountButtonsDisabled = disabled || orderBaseAmount <= 0;
	const isInputDisabled = disabled || orderBaseAmount <= 0;
	const shouldKeepOrderRounding = (inputAmount, baseInfo) => {
		const targetBaseInfo = baseInfo || roundingBaseInfo;
		if (Math.abs(targetBaseInfo.orderRoundingAmount) === 0) return false;
		return inputAmount >= targetBaseInfo.roundedBaseAmount - 1e-6;
	};
	const parseInputAmount = (value) => {
		const finalValue = String(value !== null && value !== void 0 ? value : "").trim();
		if (!finalValue) return {
			isEmpty: true,
			isInvalid: false,
			amountValue: 0
		};
		const cleanValue = finalValue.replace(/[$\s]/g, "");
		const amountValue = parseFloat(cleanValue);
		if (!Number.isFinite(amountValue)) return {
			isEmpty: false,
			isInvalid: true,
			amountValue: 0
		};
		return {
			isEmpty: false,
			isInvalid: false,
			amountValue
		};
	};
	const getDisplayedAmount = (inputAmount, baseInfo) => {
		const targetBaseInfo = baseInfo || roundingBaseInfo;
		return shouldKeepOrderRounding(inputAmount, targetBaseInfo) && Math.abs(inputAmount - targetBaseInfo.orderBaseAmount) < .01 ? targetBaseInfo.roundedBaseAmount : inputAmount;
	};
	const applyInputAmount = (value, options) => {
		const { showZeroToast = false, baseInfo } = options || {};
		const targetBaseInfo = baseInfo || roundingBaseInfo;
		const cleanValue = String(value !== null && value !== void 0 ? value : "").trim().replace(/[$\s]/g, "");
		const shouldKeepInputDecimalInput = /^\d+\.\d{0,2}$/.test(cleanValue);
		const parsedAmount = parseInputAmount(value);
		if (parsedAmount.isEmpty) {
			setAmount("");
			setRoundingAmount(0);
			return;
		}
		if (parsedAmount.isInvalid) {
			setAmount("");
			setRoundingAmount(0);
			return;
		}
		if (showZeroToast && parsedAmount.amountValue === 0) {
			Toast.fail(getText("cash-payment-amount-cannot-be-zero", "The amount cannot be 0"));
			return;
		}
		const effectiveRoundingAmount = shouldKeepOrderRounding(parsedAmount.amountValue, targetBaseInfo) ? targetBaseInfo.orderRoundingAmount : 0;
		const displayedAmount = getDisplayedAmount(parsedAmount.amountValue, targetBaseInfo);
		setAmount(shouldKeepInputDecimalInput ? cleanValue : displayedAmount.toString());
		setRoundingAmount(effectiveRoundingAmount);
	};
	useEffect(() => {
		let isCancelled = false;
		(function() {
			var _ref = _asyncToGenerator(function* () {
				let roundedBaseAmount = orderBaseAmount;
				let orderRoundingAmount = 0;
				if (roundingFunction && orderBaseAmount > 0) try {
					var _result$roundedAmount, _result$roundingDiffe;
					const result = yield roundingFunction(orderBaseAmount);
					roundedBaseAmount = (_result$roundedAmount = result === null || result === void 0 ? void 0 : result.roundedAmount) !== null && _result$roundedAmount !== void 0 ? _result$roundedAmount : orderBaseAmount;
					orderRoundingAmount = (_result$roundingDiffe = result === null || result === void 0 ? void 0 : result.roundingDifference) !== null && _result$roundingDiffe !== void 0 ? _result$roundingDiffe : 0;
				} catch (error) {
					console.warn("Failed to calculate cash rounding amount:", error);
					roundedBaseAmount = orderBaseAmount;
					orderRoundingAmount = 0;
				}
				const nextBaseInfo = {
					orderBaseAmount,
					roundedBaseAmount,
					orderRoundingAmount
				};
				if (isCancelled) return;
				setRoundingBaseInfo(nextBaseInfo);
				if (isInputDisabled) {
					setAmount("0.00");
					setRoundingAmount(0);
					return;
				}
				applyInputAmount(Number(customAmount || 0) > 0 ? customAmount !== null && customAmount !== void 0 ? customAmount : "" : String(nextBaseInfo.roundedBaseAmount || nextBaseInfo.orderBaseAmount || ""), { baseInfo: nextBaseInfo });
			});
			return function syncRoundingBaseInfo() {
				return _ref.apply(this, arguments);
			};
		})()();
		return () => {
			isCancelled = true;
		};
	}, [
		customAmount,
		balanceDueAmount,
		balanceDueTotalAmount,
		orderInfo === null || orderInfo === void 0 ? void 0 : orderInfo.isDeposit,
		roundingFunction,
		isInputDisabled,
		orderBaseAmount
	]);
	const handleCashPayInternal = () => {
		if (isAmountButtonsDisabled) return;
		if (onPaymentComplete) {
			const finalAmount = typeof amount === "number" ? amount : Number(amount) || 0;
			const effectiveRoundingAmount = shouldKeepOrderRounding(finalAmount) ? roundingBaseInfo.orderRoundingAmount : 0;
			if (finalAmount === 0 && Math.abs(effectiveRoundingAmount) === 0) {
				Toast.fail(getText("cash-payment-amount-cannot-be-zero", "The amount cannot be 0"));
				return;
			}
			const effectiveBaseAmount = roundingBaseInfo.orderBaseAmount + effectiveRoundingAmount;
			onPaymentComplete({
				type: "CASHMANUAL",
				amount: finalAmount,
				totalAmount: Number(customAmount) || 0,
				change: finalAmount - effectiveBaseAmount,
				roundingAmount: effectiveRoundingAmount
			});
		}
	};
	const { run: handleCashPay } = useDebounceFn(handleCashPayInternal, {
		wait: 500,
		leading: true,
		trailing: false
	});
	(function() {
		var _ref2 = _asyncToGenerator(function* (value) {
			if (isInputDisabled) {
				setAmount("0.00");
				setRoundingAmount(0);
				return;
			}
			applyInputAmount(value, { showZeroToast: true });
		});
		return function handleKeyboardConfirm(_x) {
			return _ref2.apply(this, arguments);
		};
	})();
	const handleReset = function() {
		var _ref3 = _asyncToGenerator(function* () {
			if (isAmountButtonsDisabled) return;
			setAmount((Math.abs(roundingBaseInfo.orderRoundingAmount) > 0 ? roundingBaseInfo.roundedBaseAmount : roundingBaseInfo.orderBaseAmount).toString());
			setRoundingAmount(roundingBaseInfo.orderRoundingAmount);
		});
		return function handleReset() {
			return _ref3.apply(this, arguments);
		};
	}();
	const keyboardOriginalValue = shouldKeepOrderRounding(Number(amount) || 0) ? String(roundingBaseInfo.roundedBaseAmount) : customAmount;
	return /* @__PURE__ */ React.createElement(CashKeyboard, {
		variant: "intact",
		originalValue: keyboardOriginalValue,
		value: amount,
		disabled,
		onChange: (value) => {
			applyInputAmount(value);
		},
		titleArea: {
			visible: true,
			title: { text: getText("cash-payment-title", "Cash Payment") },
			subtitle: {
				visible: Math.abs(roundingAmount) > 0,
				text: `${getText("cash-payment-rounding", "Rounding")}: ${formatAmount(roundingAmount, 2, amountSymbol)}`
			}
		},
		style: {
			width: "100%",
			backgroundColor: "transparent"
		},
		presets: amountButtons.slice(0, 5).map((buttonAmount) => {
			return {
				label: formatAmount(buttonAmount, 2, amountSymbol),
				value: buttonAmount
			};
		}),
		onReset: handleReset,
		onEnter: syncingLock ? void 0 : handleCashPay,
		shortcutsSize
	});
}
//#endregion
export { CashPaymentModule as default };
