"use client";

import { useState } from "react";
import Image from "next/image";
import { useRouter } from "next/navigation";
import { useTranslations } from "next-intl";

import { Offer, RetainingButton } from "@/components/domains/retaining";
import { EyeSvg } from "@/components/domains/retaining/images";
import { Spinner } from "@/components/ui";
import { BlurComponent } from "@/components/widgets";
import { performUserSubscriptionAction } from "@/entities/subscriptions/actions";
import { useLottie } from "@/hooks/lottie/useLottie";
import { useRetainingStore } from "@/providers/retaining-store-provider";
import { useToast } from "@/providers/toast-provider";
import { ROUTES } from "@/shared/constants/client-routes";
import { retainingImages } from "@/shared/constants/images";
import { ELottieKeys } from "@/shared/constants/lottie";
import { ERetainingFunnel } from "@/types";

import styles from "./SecondChancePage.module.scss";

export default function SecondChancePage() {
  const router = useRouter();
  const t = useTranslations("SecondChance");
  useLottie({
    preloadKey: ELottieKeys.loaderCheckMark2,
  });
  useLottie({
    preloadKey: ELottieKeys.confetti,
  });
  const { addToast } = useToast();

  const [activeOffer, setActiveOffer] = useState<"pause_30" | "free_chat_30">(
    "pause_30"
  );
  const [isLoadingButton, setIsLoadingButton] = useState<boolean>(false);
  const { funnel, cancellingSubscription, journey } = useRetainingStore(
    state => state
  );

  const handleOfferClick = (offer: "pause_30" | "free_chat_30") => {
    if (isLoadingButton) return;
    setActiveOffer(offer);
  };

  const handleGetOfferClick = async () => {
    if (isLoadingButton) return;
    setIsLoadingButton(true);

    const response = await performUserSubscriptionAction({
      subscriptionId: cancellingSubscription?.id || "",
      action: activeOffer,
      retainingJourney: journey || undefined,
    });

    if (response?.data?.status === "success") {
      if (activeOffer === "pause_30") {
        return router.push(ROUTES.retainingFunnelSubscriptionStopped());
      } else if (activeOffer === "free_chat_30") {
        return router.push(ROUTES.retainingFunnelFreeChatActivated());
      }
    }
    setIsLoadingButton(false);
    addToast({
      variant: "error",
      message: t("error_message"),
      duration: 5000,
    });
  };

  const handleCancelClick = async () => {
    if (isLoadingButton) return;
    if (funnel === ERetainingFunnel.Red) {
      router.push(ROUTES.retainingFunnelChangeMind());
    }
    if (funnel === ERetainingFunnel.Green) {
      // Direct cancellation instead of 60-day pause screen
      setIsLoadingButton(true);
      const response = await performUserSubscriptionAction({
        subscriptionId: cancellingSubscription?.id || "",
        action: "cancel",
        retainingJourney: journey || undefined,
      });

      if (response?.data?.status === "success") {
        return router.push(ROUTES.retainingFunnelPlanCancelled());
      }
      setIsLoadingButton(false);
      addToast({
        variant: "error",
        message: "Something went wrong. Please try again later.",
        duration: 5000,
      });
      return;
    }
    if (funnel === ERetainingFunnel.Purple) {
      return router.push(ROUTES.retainingFunnelStopFor30Days());
    }
  };

  return (
    <>
      <div className={styles.offers}>
        <Offer
          title={t.rich("offers.1.title", { br: () => <br /> })}
          description={t("offers.1.description")}
          oldPrice={t("offers.1.old-price")}
          newPrice={t("offers.1.new-price")}
          onClick={() => handleOfferClick("pause_30")}
          active={activeOffer === "pause_30"}
          image={<EyeSvg className={styles.offerImageEYE} />}
        />
        <Offer
          title={t("offers.2.title")}
          description={t("offers.2.description")}
          oldPrice={t("offers.2.old-price")}
          newPrice={t("offers.2.new-price")}
          onClick={() => handleOfferClick("free_chat_30")}
          active={activeOffer === "free_chat_30"}
          image={
            <Image
              src={retainingImages("vip_member.png")}
              alt="vip member"
              className={styles.offerImageVIP}
              width={711}
              height={609}
            />
          }
        />
      </div>

      <div className={styles.buttonOfferContainer}>
        <BlurComponent className={styles.blur} isActiveBlur={true}>
          <RetainingButton
            className={styles.buttonOffer}
            active={true}
            onClick={handleGetOfferClick}
          >
            {isLoadingButton && (
              <div className={styles.loaderContainer}>
                <Spinner />
              </div>
            )}
            {t("get_offer")}
          </RetainingButton>
        </BlurComponent>
      </div>
      <RetainingButton
        className={styles.buttonCancel}
        onClick={handleCancelClick}
      >
        {t("cancel")}
      </RetainingButton>
    </>
  );
}
