import React from 'react'
import 'intl-tel-input/build/css/intlTelInput.css'
import IntlTelInput from 'intl-tel-input/reactWithUtils'

import { Control, FieldValues, Path, useController } from 'react-hook-form'

interface PhoneNumberInputProps<T extends FieldValues> {
  controller: Control<T>
  field_name?: Path<T>
  required?: boolean
}

const PhoneNumberInput = <T extends FieldValues = FieldValues>({
  field_name = 'phone_number' as Path<T>,
  required = true,
  ...props
}: PhoneNumberInputProps<T>) => {
  const { field } = useController({
    name: field_name ?? ('phone_number' as Path<T>),
    control: props.controller,
    rules: {
      required: required
        ? {
            value: true,
            message: 'Phone Number is required',
          }
        : false,
      pattern: {
        value: /^\+(?:[0-9] ?){6,14}[0-9]$/,
        message: 'Invalid Phone Number',
      },
    },
  })

  // Handle value changes more carefully to prevent loops
  const handlePhoneChange = (value: string) => {
    // Only update if the value actually changed
    if (value !== field.value) {
      field.onChange(value)
    }
  }

  return (
    <React.Fragment>
      <div>
        <IntlTelInput
          onChangeNumber={handlePhoneChange}
          initialValue={field.value || ''}
          initOptions={{
            containerClass: 'flex flex-col w-full',
            initialCountry: 'id',
            nationalMode: true,
            strictMode: true,
            useFullscreenPopup: false,
            hiddenInput: () => {
              return {
                phone: 'phone',
                country: 'country',
              }
            },
          }}
        />
      </div>
    </React.Fragment>
  )
}

export default PhoneNumberInput
