"use client";
import { Button } from "@/components/ui/button";
import { toastError, toastSuccess } from "@/services/custom-toast";
import { useMutation, useQueryClient } from "@tanstack/react-query";
import { Loader2 } from "lucide-react";
import { useTranslations } from "next-intl";

import postData from "@/api/post-data";
export default function AuctionButton({ auction }) {
  const queryClient = useQueryClient();
  const mutation = useMutation({
    mutationFn: (values) =>
      postData({ endPoint: "/auctions/send/bidding", body: values }),
    onSuccess: async (res) => {
      if (res.status === "error" || res.error) {
        return toastError(res.message);
      } else {
        // Invalidate all auction queries (all pages) using predicate
        await queryClient.invalidateQueries({
          predicate: (query) => {
            return query.queryKey[0]?.includes("/auctions");
          },
        });
        return toastSuccess(res.message);
      }
    },
  });

  const s = useTranslations();

  function onSubmit() {
    const formData = new FormData();
    formData.append("product_id", auction?.product?.id);
    mutation.mutate(formData);
  }

  return (
    <>
      <Button
        className="border-[#008ECC] hover:text-white hover:bg-[#008ECC] !px-[55px]"
        variant="outline"
        disabled={mutation.isPending}
        onClick={onSubmit}
      >
        {mutation.isPending && <Loader2 className="animate-spin" />}
        {s("bidNow")}
      </Button>
      <p className="text-sm font-medium mt-3 text-gray-500">
        {s("updateAuctionPrices")}
      </p>
    </>
  );
}
