"use client";

import { useEffect, useRef, useTransition } from "react";
import { useRouter } from "next/navigation";
import { RefreshCw } from "lucide-react";
import { toast } from "react-hot-toast";
import { Button } from "@/components/ui/button";

export function DlmRefreshButton({ error = "" }: { error?: string }) {
  const router = useRouter(), requested = useRef(false);
  const [pending, startRefresh] = useTransition();
  useEffect(() => {
    if (pending || !requested.current) return;
    requested.current = false;
    if (error) toast.error("Refresh failed. The displayed data may be outdated.");
    else toast.success("DLM data refreshed.");
  }, [pending, error]);
  return <Button type="button" variant="outline" disabled={pending} aria-busy={pending} onClick={() => { requested.current = true; startRefresh(() => router.refresh()); }}><RefreshCw aria-hidden="true" className={pending ? "animate-spin motion-reduce:animate-none" : ""} />{pending ? "Refreshing…" : "Refresh"}</Button>;
}
