import { _objectSpread2 } from "../../../../_virtual/_@oxc-project_runtime@0.122.0/helpers/objectSpread2.js";
import { _objectWithoutProperties } from "../../../../_virtual/_@oxc-project_runtime@0.122.0/helpers/objectWithoutProperties.js";
import Input from "../../../input/index.js";
import { bankTypeMap, getCardType } from "./utils.js";
import React, { useEffect, useRef, useState } from "react";
import "./index.less";
//#region src/components/pisellInput/components/BankCard/index.tsx
const _excluded = ["onChange", "value"];
const bankCardMaxLength = (str) => {
	return str.slice(0, 19);
};
const BankCard = (props) => {
	const { onChange, value: propsValue } = props, others = _objectWithoutProperties(props, _excluded);
	const inputRef = useRef(null);
	const [_value, setValue] = useState(propsValue || "");
	const [currentBankType, setCurrentBankType] = useState();
	useEffect(() => {
		document.body.id = "body";
	}, []);
	useEffect(() => {
		setValue(bankCardMaxLength(formatBankCardNumber(`${propsValue || ""}`)));
	}, [propsValue]);
	const formatBankCardNumber = (value) => {
		return value.replace(/\D/g, "").replace(/(.{4})/g, "$1 ").trim();
	};
	const handleChange = (e) => {
		var _inputRef$current;
		const { value } = e.target;
		setCurrentBankType(getCardType(value));
		const formattedValue = formatBankCardNumber(value);
		let start = ((_inputRef$current = inputRef.current) === null || _inputRef$current === void 0 || (_inputRef$current = _inputRef$current.input) === null || _inputRef$current === void 0 ? void 0 : _inputRef$current.selectionStart) || 0;
		const val = bankCardMaxLength(formattedValue);
		setValue(val);
		onChange === null || onChange === void 0 || onChange(val.replace(/\s/g, ""));
		if (formattedValue.length > 19 || formattedValue.length < _value.length) {
			if ([
				4,
				9,
				14,
				19
			].includes(start)) start = start + 1;
			setTimeout(() => {
				var _inputRef$current2;
				(_inputRef$current2 = inputRef.current) === null || _inputRef$current2 === void 0 || _inputRef$current2.setSelectionRange(start, start);
			});
		}
	};
	return /* @__PURE__ */ React.createElement(Input, _objectSpread2(_objectSpread2({}, others), {}, {
		suffix: currentBankType ? /* @__PURE__ */ React.createElement("img", {
			className: "pisell-input-bank-card-suffix",
			src: bankTypeMap[currentBankType],
			alt: currentBankType
		}) : /* @__PURE__ */ React.createElement("span", null),
		type: "tel",
		placeholder: "1234 1234 1234 1234",
		size: "large",
		ref: inputRef,
		value: _value,
		onChange: handleChange
	}));
};
//#endregion
export { BankCard as default };
