import React, {Component} from "react";
import PhoneInput, {parsePhoneNumber, isValidPhoneNumber} from 'react-phone-number-input';
import classNames from 'classnames';

import Input from "../Input/Input";

export default class Phone extends Component {
    constructor(props) {
        super(props);
        this.state = {
            isValid: props.value ? isValidPhoneNumber(props.value) : false,
            value: props.value || '',
            focused: false
        };
    }

    setSbxInputValue = value => {
        const phoneNumber = parsePhoneNumber(value ? value : '');
        if (phoneNumber) {
            return phoneNumber.formatInternational();
        }
        return value
    };

    render() {
        const {isValid, value, focused} = this.state;
        const {validate = {}, onChange} = this.props;

        return (
            <>
                <Input
                    {...this.props}
                    ref={e => this.sbxInput = e}
                    value={value}
                    type="hidden"
                    validate={validate}
                    child={
                        <PhoneInput
                            value={value}
                            className={classNames({
                                // "PhoneInputInput_valid": isValid && focused,
                                // "PhoneInputInput_invalid": !isValid && focused
                            })}
                            {...this.props}
                            onCountryChange={value => {
                                this.props.onChangeCountry && this.props.onChangeCountry(value)
                            }}
                            onFocus={() => {
                                this.setState({focused: true})
                            }}
                            onChange={value => {
                                const isValid = value ? isValidPhoneNumber(value) : false;
                                if (onChange) {
                                    onChange(value);
                                }
                                this.setState({value, isValid: focused ? isValid : this.state.isValid}, () => {
                                    this.sbxInput.validate();
                                });
                            }}
                        />
                    }
                >
                </Input>
            </>
        )
    }
}
