import {
  Controller,
  type UseControllerProps,
  useFormContext,
} from 'react-hook-form';

import { MuiTelInput, type MuiTelInputProps } from 'mui-tel-input';

type Props = UseControllerProps & {
  textFieldProps: MuiTelInputProps;
};

function FormPhoneNumber({ name, rules, textFieldProps, defaultValue }: Props) {
  const { control, watch } = useFormContext();

  // This is done so that flag icon is displayed correctly whenever the phone number is updated
  const watchedValue = watch(name);

  return (
    <Controller
      render={({
        field: { ref: fieldRef, value, ...fieldProps },
        fieldState: { error },
      }) => (
        <MuiTelInput
          {...fieldProps}
          value={watchedValue}
          inputRef={fieldRef}
          defaultCountry="AR"
          preferredCountries={['AR', 'MX']}
          helperText={error?.message}
          variant="standard"
          error={!!error}
          {...textFieldProps}
        />
      )}
      name={name}
      rules={rules}
      control={control}
      defaultValue={defaultValue}
    />
  );
}

export default FormPhoneNumber;
