import { getRandomArbitrary, getRandomName } from "@/services/random-value";
import EmailItem, { IEmailItemProps } from "../EmailItem";
import styles from "./styles.module.css";
import { useEffect, useMemo, useRef, useState } from "react";
import { Currency } from "../PaymentTable";
import { IFunnelPaymentVariant } from "@/api/resources/Session";

const getEmails = (
  prices: number[] = [9, 9, 9, 9, 9, 5, 13.67]
): IEmailItemProps[] => {
  const emails: IEmailItemProps[] = [];

  for (let index = 0; index < 5; index++) {
    emails.push({
      email: getRandomName(),
      price: prices[getRandomArbitrary(0, prices.length)],
    });
  }

  return emails;
};

interface IEmailsListProps {
  title: string | JSX.Element | JSX.Element[];
  products: IFunnelPaymentVariant[];
  classNameContainer?: string;
  classNameTitle?: string;
  classNameEmailItem?: string;
  direction?: "up-down" | "down-up" | "left-right" | "right-left";
  currency?: Currency;
}

function EmailsList({
  title,
  products,
  classNameContainer = "",
  classNameTitle = "",
  classNameEmailItem = "",
  direction = "up-down",
  currency = Currency.USD,
}: IEmailsListProps): JSX.Element {
  const prices = useMemo(() => {
    if (!products?.length) {
      return [9, 9, 9, 9, 9, 5, 13.67];
    }

    return products.map((product) => product?.trialPrice || 0);
  }, [products]);
  const [emails, setEmails] = useState(getEmails(prices));
  const [elementIdx, setElementIdx] = useState(0);
  const itemsRef = useRef<HTMLDivElement[]>([]);

  useEffect(() => {
    let randomDelay = getRandomArbitrary(500, 5000);
    if (!elementIdx) {
      randomDelay = 0;
    }

    const itemsRefInterval = setInterval(() => {
      if (itemsRef.current[elementIdx - 1]) {
        itemsRef.current[elementIdx - 1].remove();
      }
      setEmails((prevState) => {
        const array = prevState.slice(0);
        array.push({
          email: getRandomName(),
          price: prices[getRandomArbitrary(0, prices.length)],
        });
        return array;
      });
      setElementIdx((prevState) => prevState + 1);
    }, randomDelay);
    return () => clearInterval(itemsRefInterval);
  }, [emails, elementIdx, prices]);

  return (
    <div className={`${styles.container} ${classNameContainer}`}>
      <span className={`${styles["title"]} ${classNameTitle}`}>{title}</span>
      <div className={`${styles["emails-container"]} ${styles[direction]}`}>
        {emails.map(({ email, price }, idx) => (
          <div
            className={`${styles["email-item"]} ${
              elementIdx > idx ? styles["hidden"] : ""
            }`}
            style={{
              display: elementIdx - 1 > idx ? "none" : "",
              marginLeft:
                direction === "right-left" && elementIdx > idx
                  ? `-${itemsRef.current[idx]?.offsetWidth + 10}px`
                  : 0,
            }}
            ref={(el: HTMLDivElement) => (itemsRef.current[idx] = el)}
            data-width={`-${itemsRef.current[idx]?.offsetWidth}px`}
            key={idx}
          >
            <EmailItem
              email={email}
              price={price}
              currency={currency}
              className={classNameEmailItem}
            />
          </div>
        ))}
      </div>
    </div>
  );
}

export default EmailsList;
