import React, { useEffect, useState } from "react";
import { useAppSelector, useAppDispatch } from "../../store/hooks";
import { removeNotification } from "../../store/slices/uiSlice";

export const NotificationStack: React.FC = () => {
  const notifications = useAppSelector((state) => state.ui.notifications);
  const dispatch = useAppDispatch();

  return (
    <div className="notification-stack">
      {notifications.map((notification, index) => (
        <NotificationItem
          key={notification.id}
          notification={notification}
          index={index}
          onRemove={() => dispatch(removeNotification(notification.id))}
        />
      ))}
    </div>
  );
};

const NotificationItem: React.FC<{
  notification: { id: string; message: string; type: string };
  index: number;
  onRemove: () => void;
}> = ({ notification, index, onRemove }) => {
  const [isVisible, setIsVisible] = useState(false);

  useEffect(() => {
    setTimeout(() => setIsVisible(true), 100);
  }, []);

  // Автоматическое скрытие уведомления через 4 секунды
  useEffect(() => {
    const autoHideTimer = setTimeout(() => {
      handleRemove();
    }, 4000);

    return () => clearTimeout(autoHideTimer);
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  const handleRemove = () => {
    setIsVisible(false);
    setTimeout(onRemove, 300);
  };

  return (
    <div
      className={`notification notification-${notification.type} ${
        isVisible ? "visible" : ""
      }`}
      style={{ top: `${20 + index * 70}px` }}
      onClick={handleRemove}
    >
      {notification.message}
    </div>
  );
};
