import { useEffect } from "react";
import { useSelector, useDispatch } from "react-redux";
import { AnimatePresence, motion } from "framer-motion";

// Redux
import { hideToast } from "../redux/slices/toastSlice";

// Animation Variants
const ANIMATION_VARIANTS = {
    mobile: {
        initial: { y: 100, opacity: 0 },
        animate: { y: 0, opacity: 1 },
        exit: { y: 100, opacity: 0 },
    },
    desktop: {
        initial: { x: -100, opacity: 0 },
        animate: { x: 0, opacity: 1 },
        exit: { x: -100, opacity: 0 },
    },
};

const TOAST_COLORS = {
    success: "bg-green-500",
    error: "bg-red-500",
    info: "bg-blue-500",
};

const TOAST_DURATION = 3000;

export default function Toast() {
    const { message, type, visible } = useSelector((state) => state.toast);
    const dispatch = useDispatch();
    const isMobile = typeof window !== "undefined" && window.innerWidth < 768;

    // Auto-hide toast after duration
    useEffect(() => {
        if (visible) {
            const timer = setTimeout(() => dispatch(hideToast()), TOAST_DURATION);
            return () => clearTimeout(timer);
        }
    }, [visible, dispatch]);

    const bgColor = TOAST_COLORS[type] || TOAST_COLORS.info;
    const variants = isMobile ? ANIMATION_VARIANTS.mobile : ANIMATION_VARIANTS.desktop;

    return (
        <AnimatePresence>
            {visible && (
                <motion.div
                    variants={variants}
                    initial="initial"
                    animate="animate"
                    exit="exit"
                    transition={{
                        type: "spring",
                        stiffness: 260,
                        damping: 20,
                    }}
                    className={`${bgColor} fixed z-50 text-white px-6 py-3 rounded-lg shadow-2xl max-w-xs md:max-w-sm ${
                        isMobile
                            ? "left-1/2 bottom-6 -translate-x-1/2"
                            : "top-6 left-6"
                    }`}
                    role="alert"
                >
                    <p className="text-sm md:text-base font-medium">{message}</p>
                </motion.div>
            )}
        </AnimatePresence>
    );
}
