"use client";
import fetchData from "@/api/fetch-data";
import CartCard from "@/app/ui/cart/CartCard";
import {
  HoverCard,
  HoverCardContent,
  HoverCardTrigger,
} from "@/components/ui/hover-card";
import { Separator } from "@/components/ui/separator";
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 CartRedesign({ profile }) {
  const t = useTranslations("cart");
  const [mainCart, setMainCart] = useState([]);
  const [total, setTotal] = useState(0);
  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 locale = useLocale();

  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 (
    <HoverCard openDelay={0} closeDelay={200}>
      <HoverCardTrigger className="flex cursor-pointer max-lg:flex-col items-center lg:gap-2 text-base relative">
        <CgShoppingCart size={20} className="text-main" />
        {t("title")}
        {cartLength > 0 && (
          <span className="absolute -top-2 -start-2 size-4 border border-main rounded-full text-main flex items-center justify-center text-xs">
            {cartLength}
          </span>
        )}
      </HoverCardTrigger>
      <HoverCardContent className=" lg:w-[28rem] w-80 ms-10 p-0">
        <div className="p-4">
          <h2 className="text-xl font-font-medium">
            {t("title")} <span className="text-gray-400">({cartLength})</span>
          </h2>
        </div>
        <Separator />
        <div className="p-4 space-y-4 lg:max-h-80 max-h-72 overflow-y-auto ">
          {cartLength > 0 ? (
            [...mainCart]
              .reverse()
              .map((product, index) => (
                <CartCard key={index} product={product} />
              ))
          ) : (
            <h3 className="text-center font-semibold">{t("empty")}</h3>
          )}
        </div>
        <Separator />
        {cartLength > 0 && (
          <div className="p-4 space-y-4">
            <div className="flex items-center justify-between px-8 ">
              <p>{t("total")}</p>
              <p className="text-xl ">
                {parseFloat(total * (profile ? 1 : rate)).toFixed(2)}{" "}
                <span className="text-sm text-main">{currencyShortname}</span>
              </p>
            </div>
            <Link
              href="/payment"
              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>
        )}
      </HoverCardContent>
    </HoverCard>
  );
}
