import { getRandomArbitrary, getRandomName } from "@/services/random-value";
import EmailItem, { IEmailItemProps } from "../EmailItem";
import styles from "./styles.module.css";
import { useEffect, useRef, useState } from "react";

const getEmails = (): IEmailItemProps[] => {
  const emails: IEmailItemProps[] = [];

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

  return emails;
};

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

function EmailsList({
  title,
  classNameContainer = "",
  classNameTitle = "",
  classNameEmailItem = "",
  direction = "up-down",
}: IEmailsListProps): JSX.Element {
  const [emails, setEmails] = useState(getEmails());
  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: [9, 9, 9, 9, 9, 5, 13.67][getRandomArbitrary(0, 7)],
        });
        return array;
      });
      setElementIdx((prevState) => prevState + 1);
    }, randomDelay);
    return () => clearInterval(itemsRefInterval);
  }, [emails, elementIdx]);

  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}
              className={classNameEmailItem}
            />
          </div>
        ))}
      </div>
    </div>
  );
}

export default EmailsList;
