import React, { useEffect, useMemo, useState } from "react";
import {
  ButtonType,
  Message,
  MessageSemantic,
  Semantic,
} from "@komi-app/creator-ui";
import When from "@komi-app/when";
import { useQuery } from "@tanstack/react-query";
import { getSalesServiceV1 } from "services";
import { QUOTAS } from "@komi-app/sales-sdk";
import { useFeatureIsOn, FLAGS } from "@komi-app/flags-sdk";

const STORAGE_KEY = "contacts-quota-message-dismissed";
const DISMISS_DURATION = 6 * 60 * 60 * 1000;

const ContactsQuotaMessage: React.FC = () => {
  const [isDismissed, setIsDismissed] = useState<boolean>(false);

  const useTiers = useFeatureIsOn(FLAGS.USE_TIERS_TALENT);
  const isStarterCreator = useFeatureIsOn(FLAGS.TIER_CREATOR_STARTER);
  const isTopCreator = useFeatureIsOn(FLAGS.TIER_CREATOR_TOP);

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

  const {
    data: contactsQuota,
    isLoading: isContactsQuotaLoading,
    isFetched,
  } = useQuery({
    queryFn: () => getSalesServiceV1().getQuota(QUOTAS.CONTACTS),
    queryKey: ["get-quota", QUOTAS.CONTACTS],
    enabled: isQuotaMessageEnabled,
    select: (data) => ({
      reachedQuota: (data?.usage?.quotaUsed || 0) >= data?.quota.quotaValue,
      limit: data?.quota.quotaValue,
    }),
  });

  useEffect(() => {
    const checkDismissStatus = () => {
      const dismissedData = localStorage.getItem(STORAGE_KEY);
      if (dismissedData) {
        const { timestamp } = JSON.parse(dismissedData);
        const now = Date.now();
        const isWithinTime = now - timestamp < DISMISS_DURATION;
        setIsDismissed(isWithinTime);
      }
    };

    checkDismissStatus();
  }, []);

  const handleDismiss = () => {
    const dismissData = {
      timestamp: Date.now(),
    };
    localStorage.setItem(STORAGE_KEY, JSON.stringify(dismissData));
    setIsDismissed(true);
  };

  const shouldShowMessage = useMemo(() => {
    if (
      !isQuotaMessageEnabled ||
      !isFetched ||
      isContactsQuotaLoading ||
      !contactsQuota
    ) {
      return false;
    }

    if (contactsQuota?.reachedQuota) {
      return true;
    }

    return !isDismissed;
  }, [
    isQuotaMessageEnabled,
    isFetched,
    isContactsQuotaLoading,
    contactsQuota?.reachedQuota,
    isDismissed,
  ]);

  return (
    <When
      value={shouldShowMessage}
      then={
        <Message
          semantic={
            contactsQuota?.reachedQuota
              ? MessageSemantic.WARNING
              : MessageSemantic.INFO
          }
          text={
            contactsQuota?.reachedQuota
              ? `You've reached your ${contactsQuota?.limit} contact limit. You can still capture or import more contacts, but to send emails to your subscribers, you'll need to upgrade your plan.`
              : `Your current plan allows up to ${contactsQuota?.limit} contacts. Once you reach this limit, you won't be able to send emails to your subscribers.`
          }
          buttonProps={{
            label: "Contact Us",
            href: "mailto:support@komi.io",
            type: ButtonType.LINK,
            semantic: Semantic.SECONDARY,
            size: "xsmall",
          }}
          dismissible={!contactsQuota?.reachedQuota}
          onDismiss={handleDismiss}
        />
      }
    />
  );
};

export default ContactsQuotaMessage;
