"use client";

import React, { memo, useEffect, useRef } from "react";

import { Toast } from "@/components/ui";
import { useToast } from "@/providers/toast-provider";

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

const ToastContainer = memo(() => {
  const { state, removeToast, setToastVisible, updateToastTimer } = useToast();
  const { toasts, maxVisible } = state;
  const timersRef = useRef<Map<string, number>>(new Map());

  const visibleToasts = toasts.slice(0, maxVisible);

  useEffect(() => {
    timersRef.current.forEach((timerId, toastId) => {
      const isStillVisible = visibleToasts.some(toast => toast.id === toastId);
      if (!isStillVisible) {
        clearTimeout(timerId);
        timersRef.current.delete(toastId);
      }
    });

    visibleToasts.forEach(toast => {
      if (!toast.isVisible) {
        const startTime = Date.now();
        setToastVisible(toast.id, true, startTime);

        if (toast.duration && toast.duration > 0) {
          const timerId = window.setTimeout(() => {
            removeToast(toast.id);
            timersRef.current.delete(toast.id);
          }, toast.duration);

          updateToastTimer(toast.id, timerId);
          timersRef.current.set(toast.id, timerId);
        }
      }
    });

    toasts.slice(maxVisible).forEach(toast => {
      if (toast.isVisible) {
        setToastVisible(toast.id, false);
      }
    });
  }, [
    visibleToasts,
    toasts,
    maxVisible,
    setToastVisible,
    removeToast,
    updateToastTimer,
  ]);

  useEffect(() => {
    const timers = timersRef.current;

    return () => {
      timers.forEach(timerId => {
        clearTimeout(timerId);
      });
      timers.clear();
    };
  }, []);

  return (
    <div className={styles.container}>
      {visibleToasts.map((toast, index) => (
        <div
          key={toast.id}
          className={styles.toastWrapper}
          style={
            {
              "--toast-index": index,
              "--total-toasts": visibleToasts.length,
            } as React.CSSProperties
          }
        >
          <Toast
            variant={toast.variant}
            classNameContainer={toast.classNameContainer}
            classNameToast={toast.classNameToast}
            onClose={() => removeToast(toast.id)}
          >
            {toast.message}
          </Toast>
        </div>
      ))}
    </div>
  );
});

ToastContainer.displayName = "ToastContainer";

export default ToastContainer;
