import React from "react";
import { useTypedSelector } from "redux/rootReducer";
import {
  selectProfileBuilderSubscription,
  selectUserCustomer,
} from "redux/User/selector";
import {
  SubscriptionDetails,
  subscriptionTrialForUser,
} from "utils/subscription";
import { SSXSubscriptionStage } from "constants/trial";
import { useEffect } from "react";
import SubscriptionBanner from "components/SubscriptionBanner";
import { FLAGS, useFeatureIsOn } from "@komi-app/flags-sdk";
import { useWindowSize } from "hooks";
import { useAudienceAndCampaignFeatureOn } from "../../hooks/useAudienceAndCampaignMobileBlock";
import { CustomerWithDetails } from "types/sales";

export interface PreviewLayoutBannerProps {
  url: string;
  setBannerDisplayed: (value: boolean) => void;
  isSubscribed: boolean;
  isExceedingContacts: boolean;
  customer?: CustomerWithDetails;
}

const enum LEVEL {
  INFO = `info`,
  WARNING = `warning`,
  ERROR = `error`,
}

const exceededContactsOverageMessageText = `You are over your contact limit. Overage charges will apply for any additional contacts.`;
const exceededContactsFreePlanMessageText = `You are over your contact limit.  Only the first 500 contacts can be accessed, segmented or contacted on the free plan.`;

const subscriptionExpiredMessageText = (
  props: SubscriptionDetails,
  shortMessage?: boolean,
  customer?: CustomerWithDetails | null,
) => {
  const {
    stage,
    trialRemainingDaysFormatted,
    subscriptionTrialEndAtFormatted,
  } = props;

  const expiry = `Your trial expires ${trialRemainingDaysFormatted}.`;
  const expired = "Your trial has expired.";
  const inactive = "Your subscription is inactive.";
  const hasDiscount = !!customer && customer.coupon;

  switch (stage) {
    case SSXSubscriptionStage.Early:
      return shortMessage
        ? expiry
        : hasDiscount
          ? `${expiry} ${customer.coupon?.message}`
          : `${expiry} Start a 
                        subscription now – you only get charged when your free trial ends.`;

    case SSXSubscriptionStage.Late:
      return shortMessage
        ? expiry
        : hasDiscount
          ? `${expiry} ${customer.coupon?.message}`
          : `${expiry} Set up a
                        subscription now – you will not be charged until your free trial
                        expires on ${subscriptionTrialEndAtFormatted}.`;

    case SSXSubscriptionStage.Expired:
      return shortMessage
        ? expired
        : hasDiscount
          ? `${expired} ${customer.coupon?.message}`
          : `${expired} Your URL is no longer accessible and changes
                        to your profile cannot be published.`;

    case SSXSubscriptionStage.Inactive:
      return shortMessage
        ? inactive
        : hasDiscount
          ? `${inactive} ${customer.coupon?.message}`
          : `${inactive} Your URL is no longer accessible and
                        changes to your profile cannot be published.`;

    default:
      return "";
  }
};

// Do not remove - need the subscription level to colour code the banner based on subscription stage
const subscriptionLevel = (props: SubscriptionDetails) => {
  const { stage } = props;

  switch (stage) {
    case SSXSubscriptionStage.Early:
      return LEVEL.INFO;

    case SSXSubscriptionStage.Late:
      return LEVEL.WARNING;

    case SSXSubscriptionStage.Expired:
      return LEVEL.ERROR;

    case SSXSubscriptionStage.Inactive:
      return LEVEL.ERROR;

    default:
      return LEVEL.INFO;
  }
};

const PreviewLayoutBanner = ({
  url,
  setBannerDisplayed,
  isSubscribed,
  isExceedingContacts,
  customer,
}: PreviewLayoutBannerProps) => {
  const useTiers = useAudienceAndCampaignFeatureOn(FLAGS.USE_TIERS_TALENT)  
  const isDcaAllowanceBannersEnabled = useAudienceAndCampaignFeatureOn(
    FLAGS.DCA,
  ) || useTiers;

  const subscription = subscriptionTrialForUser(
    useTypedSelector(selectProfileBuilderSubscription) || undefined,
  );

  const isOnPath = [
    "/admin",
    "/admin/header",
    "/admin/social-links",
    "/admin/modules",
    "/admin/theme",
  ].includes(url);
  const isExpiredUserOnProfileEditor =
    useFeatureIsOn(FLAGS.SSX) && isOnPath && subscription;
  const isBetaSubscriptionBannerOn =
    useFeatureIsOn(FLAGS.BETA_SUBSCRIPTION_BANNER) && isOnPath;
  const isBetaSubscriptionExtensionBannerOn =
    useFeatureIsOn(FLAGS.BETA_SUBSCRIPTION_EXTENSION_BANNER) && isOnPath;
  const isBetaTrailExpiredBanner =
    useFeatureIsOn(FLAGS.BETA_TRIAL_EXPIRED_BANNER) && isOnPath;
  const isUserExceedingContactsOnAudiencesCampaigns =
    url.includes("/audience-campaigns/") && isExceedingContacts;

  const { width } = useWindowSize();
  const isMobile = width && width <= 768;
  const isShortTrialMessageOn =
    useFeatureIsOn(FLAGS.FEAT_SB_354_SHORT_TRIAL_MESSAGE) && !!isMobile;

  useEffect(() => {
    if (
      isExpiredUserOnProfileEditor ||
      isUserExceedingContactsOnAudiencesCampaigns ||
      isBetaSubscriptionBannerOn ||
      isBetaTrailExpiredBanner
    ) {
      setBannerDisplayed(true);
    }
  }, [
    url,
    subscription.stage,
    isBetaTrailExpiredBanner,
    isBetaSubscriptionBannerOn,
  ]);

  // Subscription banner for Beta users
  if (isBetaTrailExpiredBanner) {
    const messageText =
      "Your free trial has ended and your page is no longer visible to the public. Subscribe today to reactivate.";
    return (
      <SubscriptionBanner
        messageText={messageText}
        level={LEVEL.ERROR}
        closeable={false}
        setBannerDisplayed={setBannerDisplayed}
      />
    );
  }
  if (isBetaSubscriptionBannerOn) {
    const messageText =
      "Your free trial will expire on April 27, 2023. Subscribe today to keep using Komi.";
    return (
      <SubscriptionBanner
        messageText={messageText}
        level={LEVEL.ERROR}
        closeable={false}
        setBannerDisplayed={setBannerDisplayed}
      />
    );
  }
  if (isBetaSubscriptionExtensionBannerOn) {
    const messageText =
      "Your free trial will expire on May 4, 2023. Subscribe today to keep using Komi.";
    return (
      <SubscriptionBanner
        messageText={messageText}
        level={LEVEL.ERROR}
        closeable={false}
        setBannerDisplayed={setBannerDisplayed}
      />
    );
  }
  if (subscription.stage === SSXSubscriptionStage.None) {
    setBannerDisplayed(false);
    return null;
  }

  if (isExpiredUserOnProfileEditor) {
    const messageText = subscriptionExpiredMessageText(
      subscription,
      isShortTrialMessageOn,
      customer,
    );
    const level = subscriptionLevel(subscription);
    return (
      <SubscriptionBanner
        messageText={messageText}
        level={level}
        closeable={false}
        setBannerDisplayed={setBannerDisplayed}
      />
    );
  }

  if (
    isUserExceedingContactsOnAudiencesCampaigns &&
    isDcaAllowanceBannersEnabled
  ) {
    // TODO: remove feature flag once isSubscribed and isExceedingContacts in PreviewLayout are implemented
    if (isSubscribed) {
      return (
        <SubscriptionBanner
          messageText={exceededContactsOverageMessageText}
          level={LEVEL.WARNING}
          closeable={true}
          setBannerDisplayed={setBannerDisplayed}
        />
      );
    } else {
      return (
        <SubscriptionBanner
          messageText={exceededContactsFreePlanMessageText}
          level={LEVEL.ERROR}
          closeable={false}
          setBannerDisplayed={setBannerDisplayed}
        />
      );
    }
  }
  setBannerDisplayed(false);
  return <></>;
};

export default PreviewLayoutBanner;
