import React from "react";
import { useQuery } from "@tanstack/react-query";
import { useFeatureIsOn } from "@komi-app/flags-sdk";
import { FLAGS } from "@komi-app/flags-sdk";
import { GetQuotaResponse, QUOTAS } from "@komi-app/sales-sdk";
import { getSalesServiceV1, services, getCampaignSDK } from "services";

interface QuotaData {
  hasReachedQuota: boolean;
  actionExceedsQuota: boolean;
  limit: number;
}

export const useCampaignFormQuota = (
  selectedSegments: string[]
): {
  isQuotaLimitingEnabled: boolean;
  hasQuotaLimitation: boolean;
  quotaLimitMessage: string | undefined;
  isQuotaPreventingSubmit: boolean;
} => {
  const useTiers = useFeatureIsOn(FLAGS.USE_TIERS_TALENT);
  const isStarterCreator = useFeatureIsOn(FLAGS.TIER_CREATOR_STARTER);
  const isTopCreator = useFeatureIsOn(FLAGS.TIER_CREATOR_TOP);

  const isQuotaLimitingEnabled = useTiers && isStarterCreator && !isTopCreator;

  const quotaReducer = (data: GetQuotaResponse): QuotaData => {
    const currentUsage = data?.usage?.quotaUsed || 0;
    const quotaLimit = data?.quota.quotaValue;
    const hasReachedQuota = currentUsage >= quotaLimit;

    return {
      hasReachedQuota,
      actionExceedsQuota:
        data.quota.quotaKey === QUOTAS.EMAIL_SENDS
          ? currentUsage + (segmentsFanCount || 0) + (waitingSendsCount || 0) >
            quotaLimit
          : hasReachedQuota,
      limit: quotaLimit,
    };
  };

  const { data: waitingSendsCount, isLoading: isWaitingSendsCountLoading } =
    useQuery({
      queryKey: ["get-waiting-sends-count"],
      queryFn: () => getCampaignSDK().email.getWaitingSendsCount(),
      enabled: isQuotaLimitingEnabled,
    });

  const { data: segmentsFanCount, isLoading: isSegmentsFanCountLoading } =
    useQuery({
      queryFn: () => services.segment().countMultiSegments(selectedSegments),
      queryKey: ["get-segments-fan-count", selectedSegments],
      enabled: isQuotaLimitingEnabled && selectedSegments.length > 0,
    });

  // TODO: Replace funcs with salesServiceV1.hasAvailableQuota once we have multi-facing auth implemented
  const { data: contactsQuota, isLoading: isContactsQuotaLoading } = useQuery({
    queryFn: () => getSalesServiceV1().getQuota(QUOTAS.CONTACTS),
    queryKey: ["get-quota", QUOTAS.CONTACTS],
    enabled: isQuotaLimitingEnabled,
    select: quotaReducer,
  });

  const { data: emailsQuota, isLoading: isEmailsQuotaLoading } = useQuery({
    queryFn: () => getSalesServiceV1().getQuota(QUOTAS.EMAIL_SENDS),
    queryKey: ["get-quota", QUOTAS.EMAIL_SENDS],
    enabled: isQuotaLimitingEnabled,
    select: quotaReducer,
  });

  const quotaLimitMessage = React.useMemo(() => {
    const limits = [];
    if (contactsQuota?.hasReachedQuota) {
      limits.push(`${contactsQuota?.limit} contact limit`);
    }
    if (emailsQuota?.hasReachedQuota || emailsQuota?.actionExceedsQuota) {
      limits.push(`${emailsQuota?.limit} email send limit`);
    }
    return limits.length === 0 ? "limit" : limits.join(" and ");
  }, [contactsQuota, emailsQuota]);

  const hasQuotaLimitation = React.useMemo(() => {
    return Boolean(
      (isQuotaLimitingEnabled && contactsQuota?.hasReachedQuota) ||
        emailsQuota?.hasReachedQuota ||
        emailsQuota?.actionExceedsQuota
    );
  }, [
    isQuotaLimitingEnabled,
    contactsQuota?.hasReachedQuota,
    emailsQuota?.hasReachedQuota,
    emailsQuota?.actionExceedsQuota,
  ]);

  const isQuotaPreventingSubmit = React.useMemo(() => {
    if (!isQuotaLimitingEnabled) {
      return false;
    }
    return (
      isContactsQuotaLoading ||
      hasQuotaLimitation ||
      isEmailsQuotaLoading ||
      (isSegmentsFanCountLoading && selectedSegments.length > 0) ||
      isWaitingSendsCountLoading
    );
  }, [
    isQuotaLimitingEnabled,
    isContactsQuotaLoading,
    isEmailsQuotaLoading,
    hasQuotaLimitation,
    isSegmentsFanCountLoading,
    isWaitingSendsCountLoading,
    selectedSegments,
  ]);

  return {
    isQuotaLimitingEnabled,
    hasQuotaLimitation,
    quotaLimitMessage: hasQuotaLimitation ? quotaLimitMessage : undefined,
    isQuotaPreventingSubmit,
  };
};
