import { useEffect } from "react";
import { NativeEventEmitter, NativeModules } from "react-native";
import { Platform_Android } from "../commons";

const DEFAULT_OTP_LENGTH = 6;

const Events = {
  TBASE_SMS_RETRIEVED: "TBASE_SMS_RETRIEVED",
  TBASE_SMS_RETRIEVE_ERROR: "TBASE_SMS_RETRIEVE_ERROR",
};

const { OTPCode } = NativeModules;
const eventEmitter = new NativeEventEmitter(OTPCode || {});

const retrieveOTPCode = (sms: string, otpLength = DEFAULT_OTP_LENGTH) => {
  const otpRegExp = new RegExp(`\\d{${otpLength}}`, "m");
  const otp = sms?.match(otpRegExp)?.[0];
  return otp ?? null;
};

const startNativeSmsListener = async () => {
  try {
    await OTPCode.startNativeSmsListener();
  } catch (e) {}
};

const stopNativeSmsListener = async () => {
  try {
    await OTPCode.stopNativeSmsListener();
  } catch (e) {}
};

export const useOTPCode = (props?: {
  otpLength?: number;
  onOTPReceived?: (otp: string) => void;
}) => {
  const { otpLength = DEFAULT_OTP_LENGTH, onOTPReceived } = props || {};

  useEffect(() => {
    if (!Platform_Android) return;

    startNativeSmsListener();
    const eventListener = eventEmitter.addListener(
      Events.TBASE_SMS_RETRIEVED,
      (e) => {
        const receivedSms = e?.sms;
        if (!receivedSms) return;

        const retrievedOTP = retrieveOTPCode(receivedSms, otpLength);
        if (!retrievedOTP) return;

        onOTPReceived?.(retrievedOTP);
      }
    );

    return () => {
      eventListener.remove();
      stopNativeSmsListener();
    };
  }, [otpLength, onOTPReceived]);
};
