"use client";

import { useEffect } from "react";
import { CircularProgressbar } from "react-circular-progressbar";
import { useTranslations } from "next-intl";

import { Button, Icon, IconName, Spinner, Typography } from "@/components/ui";
import { useSingleCheckout } from "@/hooks/payment/useSingleCheckout";
import { useTimer } from "@/hooks/timer/useTimer";
import { useChatStore } from "@/providers/chat-store-provider";
import { IRefillModals } from "@/services/socket/events";
import { getFormattedPrice } from "@/shared/utils/price";

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

interface RefillTimerModalProps {
  data: NonNullable<IRefillModals["oneClick"]>;
  onTimerLeft?: () => void;
  onDontWantToContinue?: () => void;
  onPaymentSuccess?: () => void;
  onPaymentError?: (error?: string) => void;
}

export default function RefillTimerModal({
  data,
  onTimerLeft,
  onDontWantToContinue,
  onPaymentSuccess,
  onPaymentError,
}: RefillTimerModalProps) {
  const { timer, product, autoTopUp } = data;
  const TIMER_SECONDS = (timer ?? 30_000) / 1000;
  const { isAutoTopUp, setIsAutoTopUp } = useChatStore(state => state);

  const t = useTranslations("RefillTimerModal");

  const { handleSingleCheckout, isLoading } = useSingleCheckout({
    onSuccess: onPaymentSuccess,
    onError: onPaymentError,
    returnUrl: typeof window !== "undefined" ? window.location.href : "",
  });

  const { seconds, isFinished } = useTimer({
    initialSeconds: TIMER_SECONDS,
  });

  useEffect(() => {
    if (isFinished) {
      onTimerLeft?.();
    }
  }, [isFinished, onTimerLeft]);

  useEffect(() => {
    setIsAutoTopUp(autoTopUp.value);
  }, [autoTopUp, setIsAutoTopUp]);

  const handleGetCredits = () => {
    if (isLoading) return;
    handleSingleCheckout({
      productId: product.id,
      key: product.key,
      isAutoTopUp,
    });
  };

  return (
    <div className={styles.container}>
      <Typography
        as="h3"
        size="xl"
        weight="bold"
        color="white"
        className={styles.title}
      >
        {t("title")}
      </Typography>
      <Typography as="p" color="white" className={styles.subtitle}>
        {t.rich("subtitle", {
          oldCredits: () => <span className={styles.oldCredits}>100</span>,
          newCredits: product.credits,
          price: getFormattedPrice(product.price, product.currency),
        })}
      </Typography>
      <div className={styles.progressContainer}>
        <div className={styles.progressTextContainer}>
          <Typography
            color="white"
            weight="bold"
            className={styles.progressTextValue}
          >
            {seconds}
          </Typography>
          <Typography size="sm" color="white" className={styles.progressText}>
            {t("seconds")}
          </Typography>
        </div>
        <CircularProgressbar
          className={styles["progress-bar"]}
          styles={{
            path: { stroke: "#fff" },
            trail: { stroke: "#a8a8aa" },
          }}
          maxValue={TIMER_SECONDS}
          minValue={0}
          value={seconds}
          strokeWidth={8}
        />
      </div>
      <Button className={styles.button} onClick={handleGetCredits}>
        {!isLoading && (
          <Typography
            color="white"
            weight="semiBold"
            className={styles.buttonText}
          >
            {t("button")}
          </Typography>
        )}
        {isLoading && <Spinner color="white" />}
      </Button>
      <Button
        className={styles.dontWantToContinue}
        onClick={onDontWantToContinue}
      >
        <Typography
          as="p"
          color="white"
          className={styles.dontWantToContinueText}
        >
          {t("dont_want_to_continue")}
        </Typography>
      </Button>
      <div className={styles.autoRefillContainer}>
        <Button
          className={styles.autoRefillIconButton}
          onClick={() => setIsAutoTopUp(!isAutoTopUp)}
        >
          <Icon
            name={IconName.Check}
            size={{ height: 20, width: 20 }}
            color={isAutoTopUp ? "#fff" : "#ffffff33"}
            className={styles.autoRefillIcon}
          />
        </Button>
        <Typography
          as="p"
          size="sm"
          color="white"
          align="left"
          className={styles.autoRefillDescription}
        >
          {t("auto_refill_description", {
            afterCredits: autoTopUp.after,
            addCredits: autoTopUp.credits,
            minutes: autoTopUp.minutes,
          })}
        </Typography>
      </div>
    </div>
  );
}
