import React, { useEffect, useMemo } from "react";
import FormInputField from "../FormInput";
import { useTranslation } from "react-i18next";
import { createPhoneNumberMask, isValidPhoneNumber } from "../../utils/inputMasking";

export const validatePhoneNumber =
  ({ t, required, currentCountry }) =>
  value => {
    if (!value || value.trim() === "") {
      if (required) {
        return t("Phone number is required");
      }
      return undefined; // Return undefined when the field is not required and empty
    }
    if (!isValidPhoneNumber(value || "", currentCountry)) {
      return t("Please enter a valid phone number");
    }
    return true;
  };

const PhoneNumber = ({
  label,
  name,
  currentCountry,
  watch,
  toolTip,
  isInfo,
  arrowDirection,
  register,
  setValue,
  errors,
  required,
  placeholder,
  disabled = false,
}) => {
  const { t } = useTranslation("components-form");
  const inputName = name ? name : "phone";
  const phoneError = errors[inputName];
  const currentPhoneNumber = watch(inputName);
  const phoneNumberMask = useMemo(() => createPhoneNumberMask(currentCountry), [currentCountry]);

  // apply masking when country or phone changes
  useEffect(() => {
    if (currentCountry && currentPhoneNumber) {
      setValue(inputName, phoneNumberMask.resolve(currentPhoneNumber), { shouldValidate: true, shouldDirty: true });
    }
  }, [currentCountry, currentPhoneNumber, phoneNumberMask]);

  return (
    <FormInputField
      id={inputName}
      type="tel"
      label={label || t("Phone number")}
      required={required}
      valid={currentPhoneNumber && isValidPhoneNumber(currentPhoneNumber, currentCountry)}
      {...register(inputName, {
        validate: validatePhoneNumber({ t, required, currentCountry }),
      })}
      placeholder={placeholder}
      error={phoneError}
      // Tooltip props
      toolTip={toolTip || t("We will only call you if there are questions regarding your order.")}
      arrowDirection={arrowDirection}
      isInfo={isInfo}
      disabled={disabled}
    />
  );
};

export default PhoneNumber;
