import { useEffect, useState } from "react";
import { Link, useHistory, useLocation } from "react-router-dom";
import { useSelector } from "react-redux";

import { FLAGS, useFeatureIsOn } from "@komi-app/flags-sdk";
import { Input, LoadingOverlay, TalentButton } from "@komi-app/components";
import When from "@komi-app/when";

import { selectUserData } from "redux/User/selector";

import {
  campaignCreateUrl,
  smsCampaignCreateUrl,
} from "constants/dca/campaigns";

import OmniChannelTable from "./OmniChannelTable";
import ChooseCampaignType from "./ChooseCampaignType/ChooseCampaignType";
import { useOmniChannelCampaignsList } from "./OmniChannelUtil";
import { useEmailDomainQuery } from "components/ProfileSettings/AudiencesAndCampaigns/EmailDomainSetup/queries";

import "../Campaigns.scss";

import { useQueryParameters } from "hooks/useQueryParameters";
import {
  ModalType,
  ToastCreationParameters,
  useModal,
  useToast,
} from "@komi-app/creator-ui";
import EmptyListView from "./EmptyListView";
import CustomDomainError from "./ListingErrorMessages/CustomDomainError";
import PhoneNumberSetupError from "./ListingErrorMessages/PhoneNumberSetupError";
import { useQuery } from "@tanstack/react-query";
import { authService, services } from "services";
import notification from "utils/notification";
import UnverifiedEmailError from "./ListingErrorMessages/UnverifiedEmailError";

const OmniChannelCampaigns = () => {
  const location = useLocation<{
    toasts: ToastCreationParameters[];
  }>();
  const [isVerificationLoading, setIsVerificationLoading] = useState(true);
  const [isUserEmailVerified, setIsUserEmailVerified] = useState(false);

  const history = useHistory();
  const user = useSelector(selectUserData);

  const customDomainQuery = useEmailDomainQuery();

  const toast = useToast();

  const useTiers = useFeatureIsOn(FLAGS.USE_TIERS_TALENT);
  const isTopCreator = useFeatureIsOn(FLAGS.TIER_CREATOR_TOP);
  const isSMSCampaignEnabled = useFeatureIsOn(FLAGS.DCA_SMS_CAMPAIGNS_SCHEDULE);
  const useSms = useTiers
    ? isSMSCampaignEnabled && isTopCreator
    : isSMSCampaignEnabled;
  const isSmartScheduleCampaignEnabled = useFeatureIsOn(
    FLAGS.SMART_SCHEDULE_TALENT,
  );

  const [searchTerm, setSearchTerm] = useState("");

  /**Fetch campaigns for the current talent */
  const {
    data: campaignsList,
    isLoading: isFetchingCampaigns,
    reset,
    currentPageIndex,
    pageCount,
    changePageIndex,
  } = useOmniChannelCampaignsList(user?.talentProfile?.id, searchTerm);

  useEffect(() => {
    const fetchEmailVerified = async () => {
      // Calling getUserProfile refreshes the cached state of
      // `emailVerified` in the authService
      await authService.getUserProfile();

      setIsUserEmailVerified(authService.emailVerified);
      setIsVerificationLoading(false);
    };

    fetchEmailVerified();
  }, [authService]);

  /**
   * Fetch segments for the current talent.
   */
  const { data: segmentsByTalent, isLoading: isFetchingSegments } = useQuery({
    queryKey: ["segmentServiceLegacy-getSegments"],
    queryFn: async () => {
      const segments = await services.segment().getSegments();
      return segments.map(({ segmentId, name }) => ({ id: segmentId, name }));
    },
    refetchOnWindowFocus: false,
  });

  const { campaignName } = useQueryParameters<{ campaignName: string }>();
  const { Modal, openModal } = useModal();

  // Show toast messages passed in location state
  useEffect(() => {
    // Display the toasts
    const state = location.state || {};
    const { toasts, ...rest } = state;

    if (toasts) {
      toasts.forEach((toastParams) => {
        toast.createToast(toastParams);
      });
    }

    // Clear the toast state
    history.replace({
      pathname: history.location.pathname,
      state: rest,
    });
  }, []);

  /**
   * Show success message when
   * "campaignName" is passed in query
   * parameters.
   * Use Toast to show success message.
   */
  useEffect(() => {
    if (campaignName) {
      if (isSmartScheduleCampaignEnabled) {
        notification.success({
          message: `You’ve scheduled a new campaign “${campaignName}”.`,
        });
      } else {
        notification.success({
          message: `You’ve scheduled your campaign “${campaignName}”.`,
        });
      }
    }
  }, [campaignName, isSmartScheduleCampaignEnabled]);

  const handleCreateCampaign = () => {
    if (useSms) openModal();
    else history.push(smsCampaignCreateUrl);
  };

  const isVerificationEnforced = !isUserEmailVerified && !isVerificationLoading;

  return (
    <div className="campaigns-page">
      <LoadingOverlay loading={isVerificationLoading} variant="light">
        {/* Error messages */}
        {isVerificationEnforced && <UnverifiedEmailError />}
        <CustomDomainError query={customDomainQuery} />
        <PhoneNumberSetupError />

        <div className="header">
          <div className="header-input">
            <Input
              data-testid="segments-filter"
              value={searchTerm}
              onValueChange={setSearchTerm}
              prefixIcon="search"
              placeholder="Search campaign"
              canClear={Boolean(searchTerm)}
            />
          </div>
          {/* Show option to create SMS campaign only when flag is enabled */}
          <When
            value={useSms}
            then={
              <TalentButton
                disabled={isVerificationEnforced}
                variant="primary"
                onClick={openModal}
              >
                NEW CAMPAIGN
              </TalentButton>
            }
            otherwise={
              <Link to={{ pathname: campaignCreateUrl }}>
                <TalentButton
                  disabled={isVerificationEnforced}
                  variant="primary"
                >
                  NEW CAMPAIGN
                </TalentButton>
              </Link>
            }
          />
        </div>

        {/* Show empty listing only when no data is present */}
        <When
          value={
            isFetchingCampaigns || isFetchingSegments || campaignsList.length
          }
          then={
            <OmniChannelTable
              searchTerm={searchTerm}
              data={campaignsList}
              loading={isFetchingCampaigns || isFetchingSegments}
              refetchTableData={reset}
              disableSorting
              currentPageIndex={currentPageIndex}
              pageCount={pageCount}
              onPageIndexChange={changePageIndex}
              segmentsByTalent={segmentsByTalent || []}
            />
          }
          otherwise={
            <EmptyListView
              isSMSCampaignEnabled={useSms}
              isEmailVerified={isUserEmailVerified}
              openModal={handleCreateCampaign}
            />
          }
        />

        {/* Modal to show new campaign type options */}
        <Modal heading="Create a new campaign" type={ModalType.ADVANCED}>
          <ChooseCampaignType />
        </Modal>
      </LoadingOverlay>
    </div>
  );
};

export default OmniChannelCampaigns;
