import React from 'react';
import { Controller, useFormContext } from 'react-hook-form';
import { MuiTelInput, matchIsValidTel, MuiTelInputCountry } from 'mui-tel-input';

import { IRHFPhoneNumberProps } from '../types';

/**
 * @description {RHFPhoneNumber} - Renders a phone number input field using React Hook Form and Material-UI.
 * @param {string} name - The name of the input field.
 * @param {string} helperText - The helper text for the input field.
 * @returns {ReactNode} - The rendered phone number input field.
 */
export const RHFPhoneNumber = ({ name, helperText }: IRHFPhoneNumberProps) => {
  const { control } = useFormContext();
  const defaultCountry: MuiTelInputCountry = 'CH';

  return (
    <Controller
      name={name}
      control={control}
      render={({ field, fieldState: { error } }) => (
        <MuiTelInput
          {...field}
          fullWidth
          defaultCountry={defaultCountry}
          value={field.value}
          onChange={(fieldValue) => {
            field.onChange(fieldValue);
          }}
          error={!!error}
          helperText={error ? error?.message : helperText}
        />
      )}
    />
  );
};

export const isValidPhoneNumber = (phoneNumber: string) => matchIsValidTel(phoneNumber);
