import { useState, useEffect, useContext, useId } from "react";
import general from "../../common/General/General";
import { ICriteria } from "../../components/QuestList/QuestList.type";
import { QuestContext } from "../../context/QuestContext";
import { TextStyle, ViewStyle } from "react-native";
import { AllEvents } from "../../common/enum";

interface crossSellingParams {
  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;
    Footer?: {
      FooterStyle?: ViewStyle;
      FooterText?: TextStyle;
      FooterIcon?: TextStyle;
    };
    Card?: {
      title?: TextStyle;
      description?: TextStyle;
      stepText?: TextStyle;
    };
    TopBar?: ViewStyle;
  };
}

function useCrossSelling({
  questId,
  questUserId,
  userToken,
  userId,
  variation,
  styleConfig,
  onError,
}: crossSellingParams) {
  const { apiKey, entityId, authenticationToken } = useContext(QuestContext);
  const [endDate, setEndDate] = useState();
  const [loading, setLoading] = useState(true);
  const [style, setStyle] = useState(styleConfig);
  // const [questDetails, setQuestDetails] = useState({
  //   title: "Your Application Progress",
  //   description: "Welcome back, Please complete your application",
  //   campaignVariationId: "",
  // });
  const [credentials, setCredentials] = useState({
    userId: questUserId,
    token: userToken,
  });

  async function fetchData(userId, token) {
    try {
      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) {
        setEndDate(response.data.endsAt);

        if (response.data.sdkConfig.uiProps) {
          setStyle(response.data.sdkConfig.uiProps.styleConfig);
        }
      } else {
        if (onError) {
          onError(AllEvents.GET_CAMPAIGN_ACTIONS, response.error, response);
        }
      }
    } catch (error) {
      if (onError) {
        onError(AllEvents.GET_CAMPAIGN_ACTIONS, error.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) {
      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 {
    // actions: criterias,
    // loading,
    // title: questDetails.title,
    // description: questDetails.description,
    // campaignVariationId: questDetails.campaignVariationId,
    // questId,
    // questUserId: credentials.userId,
    // userToken: credentials.token,
    expiryDate: endDate,
    styleConfig: style,
  };
}

export default useCrossSelling;
