"use client";

import { AnimatePresence, motion } from "framer-motion";
import styles from "@/components/ui/Toast/toast.module.css";
import { useEffect } from "react";
import { useDispatch, useSelector } from "react-redux";
import {
  deleteToastById,
  selectToast,
} from "@/utils/store/features/ui/toast.slice";

import { VscError } from "react-icons/vsc";
import { GrCircleInformation } from "react-icons/gr";
import { IoWarningOutline, IoCheckmarkCircleOutline } from "react-icons/io5";

const CreateToast = ({ icon, message, duration, id }) => {
  const icons = {
    danger: {
      icon: <VscError size={30} />,
      color: "#f44336",
    },
    warning: {
      icon: <IoWarningOutline size={30} />,
      color: "#ff9800",
    },
    success: {
      icon: <IoCheckmarkCircleOutline size={30} />,
      color: "#4caf50",
    },
    info: {
      icon: <GrCircleInformation size={30} />,
      color: "#2196f3",
    },
  };
  const dispatch = useDispatch();

  useEffect(() => {
    const _timeout = setTimeout(() => {
      dispatch(deleteToastById(id));
    }, duration * 1000);

    return () => clearTimeout(_timeout);
  }, [id, duration, dispatch]);

  return (
    <>
      <motion.div
        className={styles.toast_item}
        initial={{ opacity: 0, right: "-500px" }}
        animate={{ opacity: 1, right: 0 }}
        transition={{
          duration: 0.8,
          delay: 0.2,
          ease: [0, 0.71, 0.2, 1.01],
        }}
        exit={{
          opacity: 0,
          right: "-500px",
          transition: {
            duration: 0.15,
          },
        }}>
        <div
          className={styles.toast_icon}
          style={{ backgroundColor: icons[icon].color }}>
          {icons[icon].icon}
        </div>
        <p>{message}</p>
        <div className={styles.toast_close}></div>
        <div
          className={styles.bottom_timing}
          style={{
            backgroundColor: icons[icon].color,
            animationDuration: `${duration}s`,
          }}></div>
      </motion.div>
    </>
  );
};

const Toast = () => {
  const toasts = useSelector(selectToast);

  return (
    <div className={styles.toast_container}>
      <AnimatePresence>
        {toasts.map((toast) => (
          <CreateToast
            key={toast.id}
            icon={toast.icon}
            message={toast.message}
            duration={toast.duration}
            id={toast.id}
          />
        ))}
      </AnimatePresence>
    </div>
  );
};

export default Toast;
