import React, { useContext, useEffect, useState } from "react";
import { QuestContext } from "../../context/QuestContext";
import general from "../../common/General/General";
import useQuestNotification from "../QuestNotification/useQuestNotification";
import { TextStyle, ViewStyle } from "react-native";
import { AllEvents } from "../../common/enum";

interface streaksParams {
  questUserId?: string;
  userToken?: string;
  userId?: string;
  metric: string;
  onError?: (
    event: "GET_CAMPAIGN_ACTIONS" | "QUEST_LOGIN",
    message: string,
    data?: {}
  ) => void;
}

export default function useStreaks({
  userToken,
  questUserId,
  userId,
  metric,
  onError,
}: streaksParams) {
  const { apiKey, entityId, authenticationToken } = useContext(QuestContext);
  const [count, setCount] = useState(0);
  const [loading, setLoading] = useState(true);
  const [credentials, setCredentials] = useState({
    userId: questUserId,
    token: userToken,
  });

  async function fetchData(userId:string, token:string) {
    try {
      const response = await general.makeRequest({
        url: `/entities/${entityId}/users/${userId}/metrics/${metric}`,
        method: "GET",
        query: { userId: userId },
        headers: {
          "Content-Type": "application/json",
          userId: userId,
          token: token,
          apiKey,
        },
      });

      if (response.success) {
        setCount(response.data.counter);
      } else {
        if (onError) {
          onError(AllEvents.GET_CAMPAIGN_ACTIONS, response.error, response);
        }
      }
    } catch (er:any) {
      if (onError) {
        onError(AllEvents.GET_CAMPAIGN_ACTIONS, er.message);
      }
    }
  }

  async function externalLogin() {
    try {
      const response = await general.makeRequest({
        url: `/users/external/login`,
        method: "POST",
        headers: {
          "Content-Type": "application/json",
          apiKey,
          entityId,
          "entity-authentication-token": authenticationToken,
        },
        body: {
          externalUserId: userId,
          entityId,
        },
      });

      if (response.userId && response.token) {
        setCredentials({
          userId: response.userId,
          token: response.token,
        });
      }
      return response;
    } catch (error:any) {
      if (onError) {
        onError(AllEvents.QUEST_LOGIN, error.message);
      }
    }
  }

  useEffect(() => {
    if (questUserId && userToken) {
      (async () => {
        await fetchData(questUserId, userToken);
        setLoading(false);
      })();
    } else if (userId) {
      (async () => {
        let credentials = await externalLogin();
        await fetchData(credentials.userId, credentials.token);
        setLoading(false);
      })();
    }
  }, [questUserId, userToken, userId]);

  return {
    loading,
    count,
  };
}
