"use client";
import fetchData from "@/api/fetch-data";
import { useCurrency } from "@/stores/currency-state";
import { useQuery } from "@tanstack/react-query";
import { useLocale, useTranslations } from "next-intl";
import FallbackImage from "../shared/FallbackImage";

const formatPrice = (price, rate) => {
  // Remove commas from the price string and convert to number
  const cleanPrice =
    typeof price === "string"
      ? parseFloat(price.replace(/,/g, ""))
      : parseFloat(price);

  // Check if the result is a valid number
  if (isNaN(cleanPrice) || isNaN(rate)) {
    return "0.00"; // Fallback value if conversion fails
  }

  return (cleanPrice * rate).toFixed(2);
};

// { response: { data } }
export default function ProductsCartDetails() {
  const { rate, currencyShortname } = useCurrency();
  const t = useTranslations("checkout-info");
  const s = useTranslations();
  const locale = useLocale();

  const { data } = useQuery({
    queryKey: ["/cart/items", locale],
    queryFn: () => fetchData({ endPoint: "/cart/items" }),
  });
  const cart = data?.data?.products;
  const total = data?.data?.total;
  const offer = data?.data?.offer;
  return (
    <section className="p-4 md:px-6 lg:px-8 md:w-[430px] lg:w-[500px]  bg-white shadow-md">
      <h1 className="text-xl font-bold mt-8 mb-4">{t("display-products")}</h1>
      <ul className="space-y-6 overflow-y-auto max-h-[600px] mb-6">
        {cart?.map((item) => (
          <li
            key={item.id}
            className="flex gap-4 items-center lg:flex-row md:flex-col flex-row "
          >
            <div className="border border-gray-300 rounded-md p-4">
              <FallbackImage
                src={item.cover_photo}
                alt={item.title || "title"}
                width={75}
                height={75}
              />
            </div>
            <div className="md:text-center ">
              <h2 className="text-base md:text-xl text-[#3B3313] font-bold line-clamp-1">
                {item.title || "title"}
              </h2>
              <span className="text-base md:text-lg  font-medium text-main">
                {formatPrice(item.price, rate)}{" "}
                <span className="text-xs font-bold">
                  {currencyShortname}&nbsp;
                </span>
              </span>
              <span className="text-xs  md:text-base  text-[#3B3313] font-bold">
                {t("amount")} {item.quantity}
              </span>
            </div>
          </li>
        ))}
      </ul>

      {offer > 0 && (
        <ul className="space-y-6 border-y my-4">
          <li className="flex justify-between">
            <h3 className=" text-[#3B3313] font-bold">{t("offer")}</h3>
            <p className="font-medium ">
              {parseFloat(offer).toFixed(2)} {currencyShortname}
            </p>
          </li>
        </ul>
      )}

      <div className="flex justify-between my-4">
        <h2 className="text-lg text-dark font-bold">{t("total")}</h2>
        <h2 className="text-lg text-main font-bold">
          {(() => {
            // Ensure total and offer are valid numbers
            const numTotal =
              typeof total === "number"
                ? total
                : typeof total === "string"
                ? parseFloat(total.replace(/,/g, ""))
                : 0;

            const numOffer =
              typeof offer === "number"
                ? offer
                : typeof offer === "string"
                ? parseFloat(offer.replace(/,/g, ""))
                : 0;

            // Perform calculation only if valid numbers
            const result =
              !isNaN(numTotal) && !isNaN(numOffer)
                ? (numTotal - numOffer).toFixed(2)
                : "0.00";

            return result;
          })()}
          {currencyShortname}{" "}
        </h2>
      </div>
    </section>
  );
}
