"use client";

import { useEffect, useState } from "react";
import { useRouter, usePathname, useSearchParams } from "next/navigation";

export default function SuccessToast() {
  const router = useRouter();
  const pathname = usePathname();
  const searchParams = useSearchParams();
  const success = searchParams.get("success");
  const [message, setMessage] = useState<string | null>(null);

  useEffect(() => {
    if (!success) return;
    setMessage(success);
    const params = new URLSearchParams(searchParams.toString());
    params.delete("success");
    const query = params.toString();
    router.replace(query ? `${pathname}?${query}` : pathname, { scroll: false });
    const timer = setTimeout(() => setMessage(null), 4000);
    return () => clearTimeout(timer);
    // Only re-run when the raw `success` param changes — including searchParams/router/pathname
    // would re-fire this on every navigation once they've been mutated by the replace() above.
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [success]);

  if (!message) return null;

  return (
    <div className="fixed bottom-6 right-6 z-50 flex max-w-sm items-center gap-2 rounded-lg bg-emerald-700 px-4 py-3 text-sm font-medium text-white shadow-lg print:hidden">
      <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 20 20" fill="currentColor" className="h-5 w-5 shrink-0">
        <path
          fillRule="evenodd"
          d="M10 18a8 8 0 100-16 8 8 0 000 16zm3.857-9.809a.75.75 0 00-1.214-.882l-3.483 4.79-1.88-1.88a.75.75 0 10-1.06 1.061l2.5 2.5a.75.75 0 001.137-.089l4-5.5z"
          clipRule="evenodd"
        />
      </svg>
      <span className="flex-1">{message}</span>
      <button onClick={() => setMessage(null)} aria-label="Dismiss" className="shrink-0 text-white/80 hover:text-white">
        <svg xmlns="http://www.w3.org/2000/svg" className="h-4 w-4" fill="none" viewBox="0 0 24 24" strokeWidth={2} stroke="currentColor">
          <path strokeLinecap="round" strokeLinejoin="round" d="M6 18 18 6M6 6l12 12" />
        </svg>
      </button>
    </div>
  );
}
