"use client";
import fetchData from "@/api/fetch-data";
import CartCard from "@/app/ui/cart/CartCard";
import { Separator } from "@/components/ui/separator";
import { Sheet, SheetContent, SheetTrigger } from "@/components/ui/sheet";
import useCart from "@/stores/cart";
import { useCurrency } from "@/stores/currency-state";
import { useQuery } from "@tanstack/react-query";
import { useLocale, useTranslations } from "next-intl";
import Link from "next/link";
import { useEffect, useState } from "react";
import { CgShoppingCart } from "react-icons/cg";
import { FaArrowRight } from "react-icons/fa6";
export default function CartRedesignThree({ profile, sheet }) {
  const t = useTranslations("cart");
  const [mainCart, setMainCart] = useState([]);
  const [total, setTotal] = useState(0);
  const [open, setOpen] = useState(false);
  const locale = useLocale();

  const cartLength = mainCart?.reduce(
    (acc, item) => acc + Number(item.quantity),
    0
  );
  const { cart, total: totalFu } = useCart();
  const totalLocal = totalFu({ cart });
  const { currencyShortname, rate } = useCurrency();

  const { data } = useQuery({
    queryKey: ["/cart/items", locale],
    queryFn: () => fetchData({ endPoint: "/cart/items" }),
  });

  useEffect(() => {
    if (profile) {
      setMainCart(data?.data?.products);
      setTotal(data?.data?.total);
    } else {
      setMainCart(cart);
      setTotal(totalLocal);
    }
  }, [cart, data?.data?.products, data?.data?.total, profile, totalLocal]);

  return (
    <Sheet open={open} onOpenChange={setOpen}>
      <SheetTrigger className="flex cursor-pointer flex-col items-center lg:gap-2 relative text-xs">
        <CgShoppingCart size={sheet ? 30 : 20} />
        {!sheet && t("title")}
        {cartLength > 0 && (
          <span className="absolute -top-2 -start-2 size-5 bg-secondary rounded-full text-main flex items-center justify-center text-xs">
            {cartLength}
          </span>
        )}
      </SheetTrigger>
      <SheetContent className="overflow-y-auto">
        <div className="py-4">
          {t("title")} <span className="text-gray-400">({cartLength})</span>
        </div>
        <Separator />
        <div className="py-4 space-y-4 overflow-y-auto">
          {cartLength > 0 ? (
            mainCart.map((product, index) => (
              <CartCard key={index} product={product} />
            ))
          ) : (
            <h3 className="text-center font-semibold">{t("empty")}</h3>
          )}
        </div>
        <Separator />
        {cartLength > 0 && (
          <div className="space-y-4 ">
            <div className="flex items-center justify-between px-8 pt-4">
              <p>{t("total")}</p>
              <p className="text-xl ">
                {(() => {
                  // Check if total exists and convert to a clean number
                  const numTotal = (() => {
                    if (total === null || total === undefined) return 0;

                    // Handle string values that might contain commas
                    if (typeof total === "string") {
                      // Replace commas and other non-numeric characters except decimal point
                      return parseFloat(total.replace(/[^\d.-]/g, "")) || 0;
                    }

                    return parseFloat(total) || 0;
                  })();

                  // Ensure rate is a number
                  const numRate = parseFloat(rate) || 1;

                  // Perform the calculation safely
                  const result = (numTotal * (profile ? 1 : numRate)).toFixed(
                    2
                  );

                  // Final check to prevent any possible NaN
                  return isNaN(result) ? "0.00" : result;
                })()}
                <span className="text-sm text-main">{currencyShortname}</span>
              </p>
            </div>
            <Link
              href="/payment"
              onClick={() => setOpen(false)}
              className="py-2 text-white bg-black text font-medium w-full flex items-center justify-center gap-4 rounded-sm border-2 border-black hover:bg-white hover:text-black transition-all duration-300"
            >
              <FaArrowRight size={20} className="font-semibold" />
              {t("checkout")}
            </Link>
          </div>
        )}
      </SheetContent>
    </Sheet>
  );
}
