"use client";
import postData from "@/api/post-data";
import getUserProfile from "@/api/user/getUserProfile";
import { Button, buttonVariants } from "@/components/ui/button";
import { cn } from "@/lib/utils";
import { toastError, toastSuccess } from "@/services/custom-toast";
import { useMutation, useQuery } from "@tanstack/react-query";
import { Loader2 } from "lucide-react";
import { useLocale, useTranslations } from "next-intl";
import Link from "next/link";
import { TbShoppingBagPlus } from "react-icons/tb";
import AuctionDialog from "../../Pigeon/AuctionDialog";
import CountdownTimer from "../../Pigeon/CountdownTimer";
import AuctionCount from "../../Pigeon/Icons/AuctionCount";
import AuctionPrice from "../../Pigeon/Icons/AuctionPrice";
export default function AuctionDetails({ auctionDetails }) {
  const auctionDateline = auctionDetails?.auction?.end_date?.replace(" ", "T");
  const locale = useLocale();
  const auction = auctionDetails?.auction;
  //   const productDetails = data?.product;
  const t = useTranslations();

  // form data to buy the product
  const formData = new FormData();
  formData.append("item_id", auctionDetails?.auction?.product?.id);
  formData.append("item_quantity", 1);

  // add the product to the cart
  const mutation = useMutation({
    onMutate: () => {},
    mutationFn: () =>
      postData({
        endPoint: "/cart/add/item",
        body: formData,
      }),
    onSuccess: (response) => {
      if (response?.error) {
        return toastError(response?.message || t("somethingWentWrong"));
      }
      return toastSuccess(response?.message);
    },
  });

  // get user data
  const { data, isLoading } = useQuery({
    queryKey: ["profile", locale],
    queryFn: () => getUserProfile(),
  });

  const currentUserId = data?.id;
  const userWonId = auctionDetails?.auction?.user_win;
  const hasAuctionEnded = auctionDetails?.auction?.ended;
  const hasBeenBought = auctionDetails?.auction?.product?.bought;

  // in case of product had already been bought
  if (hasBeenBought) {
    return (
      <div className="">
        <p className="text-2xl font-bold text-main my-5 ">
          {t("productBeenBought")}
        </p>
      </div>
    );
  }

  // in case of the user won the auction
  if (userWonId == currentUserId && hasAuctionEnded && !hasBeenBought) {
    return (
      <div className="">
        <p className="text-2xl font-bold text-main my-5 ">{t("youHaveOne")}</p>
        <Button
          disabled={mutation.isPending}
          className="flex items-center gap-2  bg-main hover:bg-secondary hover:text-main rounded-full duration-150 mt-0 w-4/6 "
          onClick={() => mutation.mutate({})}
        >
          {mutation.isPending ? (
            <Loader2 className="mr-2 h-4 w-4 animate-spin" />
          ) : (
            <TbShoppingBagPlus size={20} />
          )}
          {t("addToCart")}
        </Button>
      </div>
    );
  }

  // in case of the auction ended and the user is not the winner
  if (userWonId != currentUserId && hasAuctionEnded) {
    return (
      <div className="">
        <p className="text-2xl font-bold text-main my-5 ">
          {t("thisAuctionHasEnded")}
        </p>
        <Link
          href="/"
          className={cn(buttonVariants({ variant: "default" }), "rounded-full")}
        >
          {t("checkOtherAuctions")}
        </Link>
      </div>
    );
  }

  return (
    <div className="">
      <div className="max-w-80 mb-5">
        {/* auction data */}
        <div className="flex flex-col gap-2 text-sm">
          <div className="flex justify-between items-center">
            <h2 className="flex items-center gap-1">
              <AuctionCount /> <span>{t("auction-count")}</span>
            </h2>
            <p>
              <span className="font-bold text-base">
                {auction?.bidders_count}
              </span>{" "}
              {t("person")}
            </p>
          </div>
          <div className="flex justify-between items-center">
            <h2 className="flex items-center gap-1">
              <AuctionPrice /> <span>{t("start-budget")}</span>
            </h2>
            <p>
              <span className="font-bold text-base">
                {auction?.start_budget}
              </span>{" "}
              {auction?.currency}
            </p>
          </div>
          <div className="flex justify-between items-center">
            <h2 className="flex items-center gap-1">
              <AuctionPrice /> <span>{t("lowest-bidding")}</span>
            </h2>
            <p>
              <span className="font-bold text-base">
                {auction?.lowest_bidding}
              </span>{" "}
              {auction?.currency}
            </p>
          </div>
          <div className="flex justify-between items-center">
            <h2 className="flex items-center gap-1">
              <AuctionPrice /> <span>{t("price")}</span>
            </h2>
            <p>
              <span className="font-bold text-base">
                {auction?.max_bidding}
              </span>{" "}
              {auction?.currency}
            </p>
          </div>
        </div>
        {/* the counter */}
        <div className="mt-4">
          <CountdownTimer targetDate={auctionDateline} />
        </div>
      </div>
      <div className="flex justify-center">
        {isLoading ? (
          <div className="" />
        ) : data ? (
          <AuctionDialog auction={auctionDetails?.auction} />
        ) : (
          <Link
            href="/sign-in"
            className={cn(
              buttonVariants({ variant: "outline" }),
              "border-[#008ECC] hover:text-white hover:bg-[#008ECC] !px-[55px]"
            )}
          >
            {t("YouNeedToLogIn")}
          </Link>
        )}
      </div>
    </div>
  );
}
