import { jsx as _jsx, Fragment as _Fragment, jsxs as _jsxs } from "react/jsx-runtime";
import { useEffect, useMemo } from "react";
import useModule from "../../../../../hooks/utility/useModule";
import Text from "../../../../Text";
import Input from "../../../../Input";
import { useOneUIConfig } from "../../../../../context/OneUIProvider";
/**
 * An extra form field that enables the user to input a phone number
 **/
export default function phoneFieldFactory(invalidPhoneLabel) {
    return function ({ value, question, onAnswer, error, }) {
        const { country } = question;
        const { titleVariant } = useOneUIConfig("component.form");
        const [phone] = value || ["", false];
        const phoneFormatter = useModule(() => import("google-libphonenumber").then((mod) => {
            return mod.PhoneNumberUtil.getInstance();
        }));
        const { phoneFormat, valid, error: phoneError, } = useMemo(() => {
            if (!phoneFormatter)
                return {
                    phoneFormat: phone,
                    valid: false,
                    error: "",
                };
            try {
                const phoneInstance = phoneFormatter.parseAndKeepRawInput(phone, country);
                const isPhoneValid = phoneFormatter.isValidNumber(phoneInstance);
                return {
                    phoneFormat: phoneFormatter.format(phoneInstance, 2),
                    valid: isPhoneValid,
                    error: isPhoneValid ? "" : invalidPhoneLabel,
                };
            }
            catch (e) {
                return {
                    phoneFormat: phone,
                    valid: false,
                    error: invalidPhoneLabel,
                };
            }
        }, [phone, phoneFormatter]);
        useEffect(() => {
            onAnswer("phone", question.id, [phoneFormat, valid, phoneError]);
        }, [phoneFormat, valid]);
        return (_jsxs(_Fragment, { children: [_jsx(Text, { type: titleVariant, children: question.title }), _jsx(Input, { placeholder: question.title, value: phoneFormat, onChange: ({ target: { value } }) => {
                        onAnswer("phone", question.id, [value, false, phoneError]);
                    }, error: error })] }));
    };
}
export const phoneFieldValidator = (answer) => {
    const isValid = !!answer && !!answer[1];
    return {
        isValid,
        error: answer[2],
    };
};
//# sourceMappingURL=PhoneField.js.map