import { TextInput } from "./TextInput.js";
import { countryCodesToNames } from "../utils/countryCodesToNames.js";
import { useCallback, useState } from "react";
import { jsx } from "@emotion/react/jsx-runtime";
import { AsYouType, getCountries, getCountryCallingCode } from "libphonenumber-js";
//#region src/components/PhoneInput.tsx
const defaultOptions = getCountries().map((countryCode) => {
	return {
		value: countryCode,
		label: `${getCountryCallingCode(countryCode)} (${countryCodesToNames[countryCode]})`
	};
}).sort((a, b) => a.label.localeCompare(b.label));
function getSelectWidth(value, pxPerChar) {
	return getCountryCallingCode(value).length * pxPerChar + 30;
}
function PhoneInput({ typography, onChange: onChangeProp, onBlur: onBlurProp, onFocus: onFocusProp, error: errorProp, pxPerChar = 6, defaultCountryCode = "US", borderRadius = 8 }) {
	const [countryCode, setCountryCode] = useState(defaultCountryCode);
	const [value, setValue] = useState("");
	const [width, setWidth] = useState(getSelectWidth(countryCode, pxPerChar));
	const [wasBlurred, setWasBlurred] = useState(false);
	const onChangeSelect = useCallback((newValue) => {
		setCountryCode(newValue);
		setWidth(getSelectWidth(newValue, pxPerChar));
	}, [
		setCountryCode,
		setWidth,
		pxPerChar
	]);
	const options = defaultOptions.map((option) => {
		if (option.value === countryCode) return {
			...option,
			label: `+ ${getCountryCallingCode(countryCode)}`
		};
		return option;
	});
	const onChange = useCallback((newValue) => {
		const parsedValue = newValue.startsWith("+") ? newValue.slice(1) : newValue;
		const formatter = new AsYouType(countryCode);
		const formattedValue = formatter.input(parsedValue);
		setValue(formattedValue);
		const phoneNumber = formatter.getNumber();
		if (onChangeProp && phoneNumber) onChangeProp({
			number: phoneNumber.number,
			countryCallingCode: phoneNumber.countryCallingCode,
			nationalNumber: phoneNumber.nationalNumber,
			formatted: formattedValue,
			isValid: phoneNumber.isValid()
		});
	}, [
		setValue,
		countryCode,
		onChangeProp
	]);
	const formatter = new AsYouType(countryCode);
	const formattedValue = formatter.input(value);
	const error = !formatter.isValid() && wasBlurred ? "Please enter a valid phone number." : void 0;
	return /* @__PURE__ */ jsx(TextInput, {
		select: {
			options,
			value: countryCode,
			onChange: onChangeSelect,
			width,
			height: 54
		},
		pattern: "[0-9,]*",
		inputMode: "numeric",
		value: formattedValue,
		onFocus: (focusEvent) => {
			if (onFocusProp) onFocusProp(focusEvent);
		},
		onBlur: (blurEvent) => {
			setWasBlurred(true);
			if (onBlurProp) onBlurProp(blurEvent);
		},
		onChange,
		error: errorProp || error,
		typography,
		borderRadius,
		borderWidth: .5,
		paddingY: 13.5
	});
}
//#endregion
export { PhoneInput };
