import { __rest } from "tslib";
import { jsx as _jsx } from "react/jsx-runtime";
import { useState } from 'react';
import { styled } from '@mui/material/styles';
import { TextField } from '@mui/material';
import { defineMessages, useIntl } from 'react-intl';
import { isValidPhoneNumber } from 'libphonenumber-js';
const messages = defineMessages({
    urlError: {
        id: 'ui.common.error.phone',
        defaultMessage: 'ui.common.error.phone'
    }
});
const PREFIX = 'SCPhoneTextField';
const Root = styled(TextField, {
    name: PREFIX,
    slot: 'Root',
    overridesResolver: (props, styles) => styles.root
})(({ theme }) => ({}));
const PhoneTextField = (props) => {
    // PROPS
    const { onChange, error = false, helperText = null } = props, rest = __rest(props, ["onChange", "error", "helperText"]);
    // STATE
    const [errorMsg, setErrorMsg] = useState(null);
    // HOOKS
    const intl = useIntl();
    // HANDLERS
    const handleChange = (event) => {
        if (event.target.value && !isValidPhoneNumber(event.target.value)) {
            setErrorMsg(intl.formatMessage(messages.urlError));
        }
        else if (error !== null) {
            setErrorMsg(null);
        }
        onChange && onChange(event);
    };
    // RENDER
    return _jsx(Root, Object.assign({}, rest, { onChange: handleChange, error: Boolean(errorMsg) || error, helperText: errorMsg || helperText }));
};
export default PhoneTextField;
