import { View, Text } from "react-native";
import React, { useContext, useEffect, useState } from "react";
import { QuestContext } from "../../context/QuestContext";
import useQuestNotification from "../QuestNotification/useQuestNotification";
import general from "../../common/General/General";
interface shareWithFriendParams {
  questId: string;
  questUserId?: string;
  questToken?: string;
  userId?: string;
}

export default function useShareWithFriend({
  questId,
  questUserId,
  questToken,
  userId,
}: shareWithFriendParams) {
  const { apiKey, entityId, authenticationToken } = useContext(QuestContext);
  const [loading, setLoading] = useState(true);
  const [referralLink, setReferralLink] = useState("");
  const { error } = useQuestNotification();
  const [credentials, setCredentials] = useState({
    userId: questUserId,
    token: questToken,
  });

  async function fetchData(userId, token) {
    try {
      
      (async () => {
        const response = await general.makeRequest({
          url: `/entities/${entityId}/quests/${questId}`,
          method: "GET",
          query: { userId:userId },
          headers: {
            "Content-Type": "application/json",
            userId:userId,
            token:token,
            apiKey,
       
          },
        });

        if (!response) {
          throw new Error("No response found");
        }
        
        if (!response.success || !response?.eligibilityData) {
          throw new Error(response.error || "Unable to fetch criterias");
        }

        if (response?.eligibilityData) {
          const findLink = response.eligibilityData.find(
            (item) => item.data.criteriaType == "LINK_OPEN_READ"
          );
          
          setReferralLink(findLink?.data.metadata?.linkActionUrl);
        }
    
      })();
    } catch (er) {
      error("Error fetching data");
      console.error("Error fetching criteria data:", er);
    }
  }

  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) {
      console.error("Error fetching data:", error);
    }
  }

  useEffect(() => {
    if (questUserId && questToken) {
      (async () => {
        await fetchData(questUserId, questToken);
        setLoading(false);
      })();
    } else if (userId) {
      (async () => {
        let credentials = await externalLogin();
        await fetchData(credentials.userId, credentials.token);
        setLoading(false);
      })();
    }
  }, [questUserId, questToken, userId]);

  return {
    loading,
    referralLink,
  };
}
