import { useCountry } from "@/context/CountryContext";
import { Controller } from "react-hook-form";
import { PhoneInput } from "react-international-phone";
const PhoneInputField = ({ name, control, errors }) => {
  const defaultCountry = useCountry();
  return (
    <div className="mb-3">
      {defaultCountry ? (
        <div className="form-group">
          <Controller
            name={name}
            control={control}
            rules={{
              required: "Phone number is required",
              validate: (value) =>
                /^\+(?:[0-9] ?){6,14}[0-9]$/.test(value) ||
                "Invalid phone number format",
            }}
            render={({ field }) => (
              <PhoneInput
                {...field}
                defaultCountry={defaultCountry}
                forceDialCode
                loading="lazy"
                placeholder="Phone Number"
                className={`form-control d-flex ${
                  errors[name] ? "is-invalid" : ""
                }`}
              />
            )}
          />
          {errors[name] && (
            <p className="text-danger">{errors[name].message}</p>
          )}
        </div>
      ) : (
        <div className="form-group">
          <input className="form-control" />
        </div>
      )}
    </div>
  );
};

export default PhoneInputField;
