import { useContext, useEffect, useState } from "react";
import general from "../../common/General/General";
import { QuestContext } from "../../context/QuestContext";
import { AllEvents } from "../../common/enum";
import { TextStyle, ViewStyle } from "react-native";

interface FeedBackWorkFlowParams {
  questId: string;
  questUserId?: string;
  userToken?: string;
  userId?: string;
  variation?: string;
  onError?: (
    event: "GET_CAMPAIGN_ACTIONS" | "QUEST_LOGIN",
    message: string,
    data?: {}
  ) => void;
  styleConfig?: {
    Heading?: TextStyle;
    Description?: TextStyle;
    Form?: ViewStyle;
    Label?: TextStyle;
    Input?: ViewStyle;
    PrimaryButton?: ViewStyle;
    SecondaryButton?: ViewStyle;
    Footer?: {
      FooterStyle?: ViewStyle;
      FooterText?: TextStyle;
      FooterIcon?: TextStyle;
    };
    listHeading?: TextStyle;
    listDescription?: TextStyle;
    Card?: ViewStyle;
    EmailError?: { text?: TextStyle };
    listHover?: {
      background?: ViewStyle;
      iconBackground?: ViewStyle;
      iconColor?: TextStyle;
      Heading?: TextStyle;
      Description?: TextStyle;
      IconSize?: ViewStyle;
    };
    ThanksPopup?: { ShowFooter?: true };
  };
}

export default function useFeedBackWorkFlow({
  questId,
  questUserId,
  userToken,
  userId,
  variation,
  onError,
  styleConfig,
}: FeedBackWorkFlowParams) {
  const { apiKey, entityId, authenticationToken } = useContext(QuestContext);
  const [loading, setLoading] = useState(true);
  const [demoData, setDemoData] = useState<[]>();
  const [style, setStyle] = useState(styleConfig);
  const [credentials, setCredentials] = useState({
    userId: questUserId,
    token: userToken,
  });
  async function fetchData(userId:string, token:string) {
    try {
      const response = await general.makeRequest({
        url: `/v2/entities/${entityId}/campaigns/${questId}/parent?userId=${userId}`,
        method: "GET",

        headers: {
          "Content-Type": "application/json",
          userId,
          token,
          apiKey,
        },
      });

      if (response.success) {
        setDemoData(response?.data?.childCampaignActions);
        if (response.data.sdkConfig.uiProps) {
          setStyle(response.data.sdkConfig.uiProps.styleConfig);
        }
      } else {
        if (onError) {
          onError(AllEvents.GET_CAMPAIGN_ACTIONS, response.error, response);
        }
      }
    } catch (error:any) {
      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: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 {
    actions: demoData,
    loading,
    questId,
    questUserId: credentials.userId,
    questToken: credentials.token,
    styleConfig: style,
  };
}
