import Button from "@/components/ChatsPath/ui/Button";
import styles from "./styles.module.scss";
import { useMemo, useState } from "react";
import Timer from "@/components/ChatsPath/ui/Timer";
import RefillProduct from "../RefillProduct";
import Loader, { LoaderColor } from "@/components/Loader";
import { useSelector } from "react-redux";
import { selectors } from "@/store";
import { useTranslations } from "@/hooks/translations";
import { ELocalesPlacement } from "@/locales";
import { IFunnelPaymentVariant } from "@/api/resources/Session";

interface IOutOfCreditsModalProps {
  isLoading?: boolean;
  isError?: boolean;
  products: IFunnelPaymentVariant[];
  handleClickButton: (productKey: string) => void;
}

const timerSeconds = 30;

const productsKeys = ["credits.400", "credits.500", "credits.80"];

function RefillProductsModal({
  isLoading = false,
  isError = false,
  products,
  handleClickButton,
}: IOutOfCreditsModalProps) {
  const { translate } = useTranslations(ELocalesPlacement.Chats);
  const assistant = useSelector(selectors.selectCurrentAssistant);
  const [timerValue, setTimerValue] = useState(timerSeconds);
  const [activeProduct, setActiveProduct] = useState<IFunnelPaymentVariant | null>(
    products.find((product) => product.key === "credits.400") || null
  );
  const filteredProducts = useMemo(
    () =>
      products.filter((product) => {
        return productsKeys.includes(product.key);
      }),
    [products]
  );

  return (
    <>
      <h3 className={styles.title}>
        {translate("/expert.refill_products_modal_title")}
      </h3>
      <div className={styles["timer-wrapper"]}>
        <Timer
          seconds={timerValue}
          onChangeSeconds={(seconds: number) => setTimerValue(seconds)}
        />
        <div className={styles["timer-text"]}>
          <h5>{assistant?.name}</h5>
          <p>{translate("/expert.refill_products_modal_description")}</p>
        </div>
      </div>
      <div className={styles["products-wrapper"]}>
        {filteredProducts.map((product) => (
          <RefillProduct
            isActive={activeProduct?.id === product.id}
            isOneTimeOffer={false}
            // credits={product.description}
            credits={0}
            price={product.price / 100}
            onClick={() => setActiveProduct(product)}
            key={product.id}
          />
        ))}
      </div>
      <div className={styles["button-wrapper"]}>
        <Button
          classNameContainer={styles.button}
          onClick={() => handleClickButton(activeProduct?.key || "")}
          disabled={!activeProduct || isLoading}
        >
          {isLoading && <Loader color={LoaderColor.White} />}
          {!isLoading && translate("continue")}
        </Button>
        {isError && (
          <span className={styles.error}>
            {translate("/expert.something_went_wrong")}
          </span>
        )}
      </div>
    </>
  );
}

export default RefillProductsModal;
