import { useQueryParameters } from "hooks/useQueryParameters";
import { useEffect, useState } from "react";
import { SMSCampaign } from "types/campaigns";
import {
  getAssignedNumbers,
  getCampaignDetails,
} from "./SMSCampaignForm/campaignUtils";
import SMSCampaignForm from "./SMSCampaignForm/SMSCampaignForm";
import { Page } from "@komi-app/creator-ui";
import { useTypedSelector } from "redux/rootReducer";
import { selectUserData } from "redux/User/selector";
import { initProfileId } from "services";
import notification from "utils/notification";
const SMSCampaignEditPage: React.FC<{}> = () => {
  const [servicesInitialized, setServicesInitialized] =
    useState<boolean>(false);
  const [campaignData, setCampaignData] = useState<SMSCampaign | undefined>();
  const [isFetchingCampaign, setIsFetchingCampaign] = useState<boolean>(false);
  const [isFetchingNumbers, setIsFetchingNumbers] = useState<boolean>(true);
  const [assignedNumber, setAssignedNumber] = useState<string>("");
  const user = useTypedSelector(selectUserData);

  const { campaignId } = useQueryParameters<{ campaignId: string }>();

  /** Our page is loaded before the SDKs are
   *  initialized. To fix this, we need to
   *  call the initProfileId functions in SDK.
   */
  useEffect(() => {
    if (!user?.talentProfile?.id) return;
    initProfileId(user.talentProfile.id);

    getTalentPhoneNumbers();
    if (campaignId) populateCampaign();
  }, [user]);

  async function getTalentPhoneNumbers() {
    setIsFetchingNumbers(true);
    const assignedNumbers = await getAssignedNumbers();
    if (assignedNumbers && assignedNumbers.length)
      setAssignedNumber(assignedNumbers[0].phoneNumber);
    setIsFetchingNumbers(false);
  }

  async function populateCampaign() {
    try {
      //Enable loader as campaigns are being fetched
      setIsFetchingCampaign(true);
      const campaignDetails = await getCampaignDetails(campaignId);
      setCampaignData(campaignDetails);
      //Stop loader as campaigns are loaded
      setIsFetchingCampaign(false);
    } catch (error: any) {
      notification.error({
        message: `Unable to fetch campaign data.`,
      });
    }
  }

  return (
    <Page isLoading={isFetchingCampaign || isFetchingNumbers}>
      <SMSCampaignForm
        existingCampaignData={campaignData}
        assignedNumber={assignedNumber}
      />
    </Page>
  );
};
export default SMSCampaignEditPage;
