import React from 'react'
import 'intl-tel-input/build/css/intlTelInput.css'
import IntlTelInput from 'intl-tel-input/reactWithUtils'
import { ControllerRenderProps } from 'react-hook-form'

interface PhoneNumberInputProps {
  field: ControllerRenderProps
}

const PhoneNumberInput: React.FC<PhoneNumberInputProps> = ({ field }) => {
  return (
    <IntlTelInput
      onChangeNumber={field.onChange}
      initialValue={field.value}
      initOptions={{
        containerClass: 'flex flex-col w-full',
        initialCountry: 'auto',
        nationalMode: true,
        strictMode: true,
        useFullscreenPopup: false,
        hiddenInput: () => {
          return {
            phone: 'phone',
            country: 'country',
          }
        },
        geoIpLookup: function (success, failure) {
          fetch('https://ipapi.co/json')
            .then(function (res) {
              return res.json()
            })
            .then(function (data) {
              success(data.country_code)
            })
            .catch(function () {
              failure()
            })
        },
      }}
    />
  )
}

export default PhoneNumberInput
