import { useState, useEffect, useRef } from "react";

export default function SaveToast({ message, onDismiss }) {
  const [exiting, setExiting] = useState(false);
  const timerRef = useRef(null);
  const exitRef = useRef(null);

  useEffect(() => {
    if (!message?.type) return;
    setExiting(false);
    timerRef.current = setTimeout(() => setExiting(true), 3000);
    return () => {
      if (timerRef.current) clearTimeout(timerRef.current);
    };
  }, [message?.type, message?.text]);

  useEffect(() => {
    if (!exiting) return;
    exitRef.current = setTimeout(() => onDismiss(), 300);
    return () => {
      if (exitRef.current) clearTimeout(exitRef.current);
    };
  }, [exiting, onDismiss]);

  if (!message?.type) return null;

  const isSuccess = message.type === "success";

  const SuccessIcon = () => (
    <svg className="w-5 h-5 flex-shrink-0 text-green-600" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
      <path strokeLinecap="round" strokeLinejoin="round" d="M9 12l2 2 4-4m6 2a9 9 0 11-18 0 9 9 0 0118 0z" />
    </svg>
  );

  const ErrorIcon = () => (
    <svg className="w-5 h-5 flex-shrink-0 text-red-600" fill="none" viewBox="0 0 24 24" stroke="currentColor" strokeWidth={2}>
      <path strokeLinecap="round" strokeLinejoin="round" d="M12 8v4m0 4h.01M21 12a9 9 0 11-18 0 9 9 0 0118 0z" />
    </svg>
  );

  return (
    <div
      role="alert"
      aria-live="polite"
      className={`fixed top-4 right-4 z-[100] px-4 py-3 rounded-lg border shadow-lg bg-white flex items-center gap-3 ${exiting ? "save-toast-exit" : "save-toast-enter"}`}
      style={{ maxWidth: "min(360px, calc(100vw - 2rem))" }}
    >
      {isSuccess ? <SuccessIcon /> : <ErrorIcon />}
      <p
        className={`text-sm font-medium ${isSuccess ? "text-green-700" : "text-red-700"}`}
      >
        {message.text}
      </p>
    </div>
  );
}
