"use client";
import { buttonVariants } from "@/components/ui/button";
import { ShineBorder } from "@/components/ui/shine-border";
import { SparklesText } from "@/components/ui/sparkel-text";
import { cn } from "@/lib/utils";
import { useTranslations } from "next-intl";
import Link from "next/link";
import FallbackImage from "../shared/FallbackImage";
import AuctionButton from "./AuctionButton";
import CountdownTimer from "./CountdownTimer";
import AuctionCount from "./Icons/AuctionCount";
import AuctionPrice from "./Icons/AuctionPrice";

export default function AuctionCard({ auction, profile }) {
  const t = useTranslations();
  const bidders = auction?.bidders;
  const showBidders = Array.isArray(bidders) && bidders?.length > 0;
  const auctionDateline = auction?.end_date?.replace(" ", "T");
  const productDetails = auction?.product;
  // Helper function to safely parse numbers with proper decimal handling
  const parsePrice = (value) => {
    if (!value) return 0;
    const parsed = parseFloat(value);
    return isNaN(parsed) ? 0 : Math.round(parsed * 100) / 100; // Ensures max 2 decimal places
  };

  // Helper function to format price display
  const formatPrice = (value) => {
    const price = parsePrice(value);
    return price % 1 === 0 ? price.toString() : price.toFixed(2);
  };

  const startBudget = parsePrice(auction?.start_budget);
  const maxBidding = parsePrice(auction?.max_bidding);
  const bidIncrement = parsePrice(0.1 * startBudget);
  const nextBidding =
    maxBidding > 0 ? maxBidding + bidIncrement : startBudget * 1.1;
  const currentPrice = maxBidding > 0 ? maxBidding : startBudget * 1.1;

  return (
    <section className="border flex flex-col justify-between bg-white relative p-3 lg:p-6 rounded-[6px] mt-24 space-y-5">
      <div className="absolute w-52 h-36 -top-24 right-1/2 translate-x-1/2">
        <FallbackImage
          fill
          className="mx-auto size-52 object-contain"
          src={auction?.product?.cover_photo || ""}
          alt="auction card"
        />
      </div>

      <div className="space-y-5">
        <Link
          href={`/products/${auction?.product?.id}`}
          className="text-center font-bold text-xl hover:underline hover:text-[#008ECC] line-clamp-1  my-4 mt-8"
        >
          {productDetails?.title}
        </Link>
        {auction?.product?.sku && (
          <p className="text-sm sm:text-lg font-bold text-gray-500 my-5">
            {auction?.product?.sku}
          </p>
        )}
      </div>
      <div className="space-y-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 || 0}
            </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">
              {formatPrice(startBudget)}
            </span>{" "}
            {auction?.currency}
          </p>
        </div>
        <div className="flex justify-between items-center">
          <h2 className="flex items-center gap-1">
            <AuctionPrice /> <span>{t("next-bidding")}</span>
          </h2>
          <p>
            <span className="font-bold text-base">
              {formatPrice(nextBidding)}
            </span>{" "}
            {auction?.currency}
          </p>
        </div>
        {/* price  */}
        <div className="flex justify-between items-center relative p-2 rounded-md">
          <ShineBorder
            shineColor={["#A07CFE", "#FE8FB5", "#FFBE7B"]}
            duration={100}
          />
          <SparklesText sparklesCount={3}>
            <h2 className="flex items-center gap-1 animate-fade-in-out">
              <AuctionPrice /> <span>{t("last-bidding")}</span>
            </h2>
          </SparklesText>
          <SparklesText sparklesCount={3}>
            <p className="font-bold text-base animate-fade-in-out">
              {auction?.currency}
              <span className="font-bold text-base mx-1">
                {formatPrice(currentPrice)}
              </span>
            </p>
          </SparklesText>
        </div>
      </div>
      <CountdownTimer targetDate={auctionDateline} />

      {showBidders ? (
        <div className="flex flex-col gap-2">
          <h4>{t("bidders")}</h4>
          <div className="flex justify-between mb-2">
            <p>{t("bidderName")} :</p>
            <p>{t("bidderBidding")} :</p>
          </div>
          <div className="h-[200px] overflow-y-auto">
            {bidders?.map((bider) => (
              <div key={bider.bid_id} className="space-y-2">
                {/* separator */}
                <div className="w-[20%] h-[2px] bg-[#233040] mx-auto my-2" />

                <div className="flex justify-between font-medium p-2 bg-slate-100 rounded-md m-2">
                  <p>{bider.name + " " + bider.lastname}</p>
                  <p>{bider.bidding}</p>
                </div>
              </div>
            ))}
          </div>
        </div>
      ) : (
        <div className="h-[272px]" />
      )}
      <div className="text-center">
        {profile ? (
          auction?.ended ? (
            <p className="text-sm font-medium text-red-500 border-red-500 bg-red-50 border p-4 rounded-sm">
              {t("auctionEnded")}
            </p>
          ) : (
            <>
              <AuctionButton auction={auction} />
            </>
          )
        ) : (
          <Link
            href="/sign-in"
            className={cn(
              buttonVariants({ variant: "outline" }),
              "border-[#008ECC] hover:text-white hover:bg-[#008ECC] !px-[55px]"
            )}
          >
            {t("YouNeedToLogIn")}
          </Link>
        )}
      </div>
    </section>
  );
}
