"use client";

import { useSelector, useDispatch } from "react-redux";
import { useEffect } from "react";
import { hideToast } from "@/redux/slices/toastSlice";

export default function Toast() {
  const dispatch = useDispatch();
  const { message, type, visible } = useSelector((state) => state.toast);

  useEffect(() => {
    if (visible) {
      const timer = setTimeout(() => {
        dispatch(hideToast());
      }, 3000);

      return () => clearTimeout(timer);
    }
  }, [visible, dispatch]);

  if (!visible) return null;

  const bgColor = {
    success: "bg-green-50 border-green-200 text-green-700",
    error: "bg-red-50 border-red-200 text-red-700",
    warning: "bg-yellow-50 border-yellow-200 text-yellow-700",
    info: "bg-blue-50 border-blue-200 text-blue-700",
  }[type];

  const progressColor = {
    success: "bg-green-500",
    error: "bg-red-500",
    warning: "bg-yellow-500",
    info: "bg-blue-500",
  }[type];

  return (
    <div className="fixed top-5 left-5 z-50 max-w-sm animate-in slide-in-from-top">
      <div
        className={`border p-4 rounded-lg shadow-lg ${bgColor}`}
        role="alert"
      >
        <p className="font-medium text-sm">{message}</p>
        <div className={`h-1 w-full ${progressColor} mt-2 rounded-full`}></div>
      </div>
    </div>
  );
}
