import React, { useState, useEffect } from 'react';

import classNames from 'classnames/bind';
import FormElement from 'components/structure/FormElement';
import FieldWrapper from 'components/structure/FieldWrapper';
import ReactPhoneInput from 'react-phone-input-2';
import styleIdentifiers from './phoneInput.scss';
import '!style-loader!css-loader!react-phone-input-2/lib/style.css';

const styles = classNames.bind(styleIdentifiers);

interface OwnProps {
  className?: string;
  label?: string;
  inputClassName?: string;
  buttonClassName?: string;
  dropdownClassName?: string;
  searchClassName?: string;
  phoneWrapperClassName?: string;
  containerClassName?: string;
  inputProps?: {
    name?: string;
    required?: boolean;
    autoFocus?: boolean;
  };
}

export type PhoneInputProps = FormElementProps & FieldWrapperProps & OwnProps;

const PhoneInput = (props: PhoneInputProps) => {
  const {
    input,
    className,
    label,
    country,
    inputClassName,
    buttonClassName,
    dropdownClassName,
    searchClassName,
    phoneWrapperClassName,
    containerClassName,
    inputProps,
  } = props;

  const handleOnChange = (event: Event) => {
    const { onChange } = input;
    input.onChange(event);
    if (onChange) onChange(event);
  };

  return (
    <FormElement {...props} className={styles('phone-input', className)}>
      <FieldWrapper {...props} noPadding>
        <div className={styles('phone', label && 'has-label', phoneWrapperClassName)}>
          <ReactPhoneInput
            value={input.value}
            onChange={handleOnChange}
            country={country}
            containerClass={styles('container', containerClassName)}
            inputClass={styles('input', inputClassName)}
            buttonClass={styles('button', buttonClassName)}
            dropdownClass={styles('dropdown', dropdownClassName)}
            searchClass={styles('search-bar', searchClassName)}
            inputProps={inputProps}
            specialLabel=""
          />
        </div>
      </FieldWrapper>
    </FormElement>
  );
};

export default PhoneInput;
