import { toast, type ToastOptions, type ToastPosition } from "react-toastify";

export type ToastType = "success" | "error" | "warning" | "default";

const getPosition = (): ToastPosition => {
    if (typeof window === "undefined") return "bottom-right";
    return window.innerWidth > 640 ? "bottom-right" : "bottom-center";
};

const baseClass =
    "rounded-2xl border px-4 py-3 shadow-lg flex items-start gap-3 w-full";

const toastStyles = {
    success:
        "border-primary !bg-secondary !text-light",
    error:
        "border-[var(--red)] !bg-secondary !text-red",
    warning:
        "border-yellow-400 !bg-secondary !text-yellow-700",
    default:
        "border-[var(--primary)] !bg-secondary !text-light",
};

export const Toast = (
    type: ToastType,
    message?: string,
    duration?: number
) => {
    const options: ToastOptions = {
        autoClose: duration === 0 ? false : duration ?? 2000,
        // autoClose: false,
        position: getPosition(),
        closeOnClick: true,
        pauseOnHover: true,
        hideProgressBar: false,
        className: `${baseClass} ${toastStyles[type]}`,
        progressClassName:
            type === "error"
                ? "bg-[var(--red)]"
                : "bg-[var(--primary)]",
        toastId: message, // Prevent duplicate toasts
    };

    switch (type) {
        case "success":
            toast.success(message ?? "Operation successful!", options);
            break;
        case "error":
            toast.error(message ?? "Something went wrong!", options);
            break;
        case "warning":
            toast.warn(message ?? "Warning!", options);
            break;
        default:
            toast(message ?? "Notification", options);
    }
};
