import { ViewStyle, TextStyle } from "react-native";
import { useContext, useEffect, useState } from "react";
import { QuestContext } from "../../context/QuestContext";
import general from "../../common/General/General";
import { AllEvents } from "../../common/enum";
interface referralParams {
  questId: string;
  questUserId?: string;
  userToken?: string;
  userId?: string;
  variation?: string;
  onError?: (
    event: "GET_CAMPAIGN_ACTIONS" | "QUEST_LOGIN",
    message: string,
    data?: {}
  ) => void;
  styleConfig?: {
    Form?: ViewStyle;
    Heading?: TextStyle;
    Description?: TextStyle;
    Input?: ViewStyle;
    Label?: TextStyle;
    // TextArea?: ViewStyle,
    PrimaryButton?: ViewStyle;
    // SecondaryButton?: ViewStyle,
    Modal?: ViewStyle;
    Footer?: {
      FooterStyle: ViewStyle;
      FooterText: TextStyle;
      FooterIcon: TextStyle;
    };
    // Icon?: ViewStyle,
  };
}

export default function useReferral({
  questId,
  questUserId,
  userToken,
  userId,
  variation,
  onError,
  styleConfig,
}: referralParams) {
  const { apiKey, entityId, authenticationToken } = useContext(QuestContext);
  const [loading, setLoading] = useState(true);
  const [referralCode, setReferralCode] = useState("");
  const [style, setStyle] = useState(styleConfig);
  const [credentials, setCredentials] = useState({
    userId: questUserId,
    token: userToken,
  });
  const [questDetails, setQuestDetails] = useState({
    title: "Referral",
    description: "Refer Earn",
  });

  async function fetchData(userId:string, token:string) {
    try {
      (async () => {
        const response = await general.makeRequest({
          url: `/v2/entities/${entityId}/campaigns/${questId}?variation=${
            variation || "default"
          }`,
          method: "GET",

          headers: {
            "Content-Type": "application/json",
            userId: userId,
            token: token,
            apiKey,
          },
        });

        if (response.success == true) {
          setReferralCode(response.data.referralCode);
          setQuestDetails({
            title: response?.data?.title || "Referral",
            description: response?.data?.description || "Refer Earn",
          });
          if (response.data.sdkConfig.uiProps) {
            setStyle(response.data.sdkConfig.uiProps.styleConfig);
          }
        } else {
          if (onError) {
            onError(AllEvents.GET_CAMPAIGN_ACTIONS, response.error, response);
          }
        }

        // if (response?.data) {
        //   const findLink = response.data.actions.find(
        //     (item) => item.data.criteriaType == "LINK_OPEN_READ"
        //   );

        //   setReferralLink(findLink?.data.metadata?.linkActionUrl);
        // }
      })();
    } 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,
    referralCode,
    title: questDetails.title,
    description: questDetails.description,
    styleConfig: style,
  };
}
