"use client";
import { getToken } from "@/actions/cookies";
import addToCart from "@/api/cart/addToCart";
import updateQuantity from "@/api/cart/update-quantity";
import fetchData from "@/api/fetch-data";
import getUserProfile from "@/api/user/getUserProfile";
import { Separator } from "@/components/ui/separator";
import { toastError, toastSuccess } from "@/services/custom-toast";
import useCart from "@/stores/cart";
import { useCurrency } from "@/stores/currency-state";
import { useQuery, useQueryClient } from "@tanstack/react-query";
import clsx from "clsx";
import { useLocale, useTranslations } from "next-intl";
import { useEffect, useState } from "react";
import AuctionButton from "../../Pigeon/AuctionButton";
import Images from "../../singleProduct/Images";
import Rate from "../Rate";
import ProductFormComponentRedesignThree from "./ProductFormComponentRedesignThree";

export default function DetailsRedesign2({
  data,
  customFormInputs,
  images,
  videoUrl,
}) {
  const product = data?.product;
  const feature = data?.features?.length > 0 ? data?.features?.[0] : null;
  const categories = data?.main_category?.translation?.title;
  const locale = useLocale();

  const [featureIndx, setFeatureIndx] = useState(0);
  const featurePrice = feature?.options?.[featureIndx]?.price;
  const queryClient = useQueryClient();
  const { currencyShortname, rate } = useCurrency();
  const [itemExist, setItemExist] = useState(false);
  const [quantity, setQuantity] = useState(1);
  const [loading, setLoading] = useState(false);
  const c = useTranslations("cart");
  const t = useTranslations("single-product");
  const s = useTranslations();
  const hasPrice = !!product?.price;
  const {
    addToCart: addToCartLocale,
    incrementQuantity,
    cart: cartLocal,
  } = useCart();
  const { data: cart, isError } = useQuery({
    queryKey: ["/cart/items", locale],
    queryFn: () => fetchData({ endPoint: "/cart/items" }),
  });

  useEffect(() => {
    async function fetchCart() {
      const token = await getToken();

      if (!token) {
        const localItemExist = cartLocal?.find(
          (item) => item?.id === product?.id
        );
        if (localItemExist) {
          setQuantity(Number(localItemExist?.quantity));
          setItemExist(true);
        } else {
          setQuantity(1);
          setItemExist(false);
        }
        return;
      }

      if (isError) {
        toastError(cart?.message);
      } else if (Array.isArray(cart?.data?.products)) {
        const item = cart?.data?.products?.find(
          (item) => item?.id === product?.id
        );
        if (item) {
          setQuantity(Number(item?.quantity));
          setItemExist(true);
        } else {
          setQuantity(1);
          setItemExist(false);
        }
      }
    }

    fetchCart();
  }, [cart?.data?.products, cart?.message, cartLocal, isError, product?.id]);

  function handleIncrement() {
    setQuantity(quantity + 1);
  }

  function handleDecrement() {
    setQuantity(quantity - 1);
  }
  async function addProductToCart() {
    setLoading(true);
    const user = await getUserProfile();

    if (user) {
      if (itemExist) {
        // If item exists in the cart, update the quantity
        const { message, code } = await updateQuantity(product.id, quantity);
        setLoading(false);

        if (code !== 200) {
          toastError(message);
          return;
        }
        toastSuccess(message);
      } else {
        // If item does not exist, add it to the cart
        const { message, code } = await addToCart(product.id, quantity, {
          type: feature?.type,
          id: feature?.options[featureIndx]?.id,
        });
        setLoading(false);

        if (code !== 200) {
          toastError(message);
          return;
        }
        toastSuccess(message);
      }

      queryClient.refetchQueries({ queryKey: ["/cart/items"] }); // Refetch cart
    } else {
      // If no token, handle local cart logic
      if (itemExist) {
        incrementQuantity(product.id, quantity); // Increment the quantity locally
      } else {
        addToCartLocale(product); // Add locally with the specified quantity
        incrementQuantity(product.id, quantity); // Increment the quantity locally
      }
      setLoading(false);
      toastSuccess(itemExist ? c("update-success") : c("add-success"));
    }
  }

  return (
    <div className="w-full">
      <div className=" text-sm md:text-base flex flex-col-reverse lg:flex-row w-full lg:gap-5 gap-3">
        <div className="flex-1 min-w-[50%] flex flex-col gap-5">
          <div>
            <h1 className="lg:text-3xl md:text-2xl text-main text-xl my-5 text-start">
              {product?.title}
            </h1>
            {/* sku - the product code */}

            {product?.sku && (
              <p className="text-sm sm:text-lg font-bold text-gray-500 my-5">
                {product?.sku}
              </p>
            )}

            {!data.has_auction && (
              <div className="flex items-center gap-2 ">
                <Rate rating={product.rate} />
                <div className="text-gray-400 text-sm flex items-center gap-1">
                  <p>
                    ({product?.comments?.length} {t("reviews")})
                  </p>
                </div>
              </div>
            )}
          </div>

          {/* Price and discount and feature price */}
          {/* Main price */}
          {!data.has_auction && hasPrice && (
            <div className="flex text-sm font-bold lg:text-xl 2xl:text-2xl items-center gap-2">
              {product.discount && (
                <p className="flex items-center">
                  {currencyShortname}{" "}
                  {(
                    (product.price -
                      product.price * (product.discount / 100) +
                      Number(featurePrice ?? 0)) *
                    rate
                  ).toFixed(2)}
                </p>
              )}
              <p
                className={clsx({
                  "line-through text-gray-500 text-xs lg:text-lg 2xl:text-xl font-normal":
                    product.discount,
                })}
              >
                {currencyShortname}{" "}
                {((product.price + Number(featurePrice ?? 0)) * rate).toFixed(
                  2
                )}
              </p>
            </div>
          )}

          {/* Discount percentage */}
          {!data.has_auction && hasPrice && product.discount && (
            <div className="flex items-center gap-2 text-red-600">
              {t("discount")}:{" "}
              {(product.price * (product.discount / 100) * rate).toFixed(2)} (
              {product.discount / 100}%)
            </div>
          )}

          {/* Feature price */}
          {!data.has_auction && hasPrice && !!featurePrice && (
            <p>
              {t(`price-${feature?.type}`)}:{" "}
              {(Number(featurePrice) * rate).toFixed(2)} {currencyShortname}
            </p>
          )}

          {/* Display Features */}
          <p className="mb-2">{feature?.title}</p>
          {!data.has_auction &&
            feature &&
            (feature?.type === "color" ? (
              <div className="flex gap-2 items-center flex-wrap">
                {feature?.options?.map((option, indx) => (
                  <div
                    key={option?.id}
                    style={{ backgroundColor: option?.title }}
                    className={clsx(
                      "h-7 animate-out duration-500 px-6 cursor-pointer text-sm rounded-full border-2",
                      {
                        "border-main": featureIndx === indx,
                      }
                    )}
                    onClick={() => setFeatureIndx(indx)}
                  ></div>
                ))}
              </div>
            ) : (
              <div className="flex gap-1 items-center flex-wrap">
                {feature?.options?.map((option, indx) => (
                  <div
                    key={option?.id}
                    className={clsx(
                      "py-2 px-4 animate-out duration-500 cursor-pointer text-center text-sm font-semibold rounded-full border",
                      {
                        "border-main bg-main text-white": featureIndx === indx,
                      }
                    )}
                    onClick={() => setFeatureIndx(indx)}
                  >
                    {option?.title}
                  </div>
                ))}
              </div>
            ))}
          {/* /////////// */}
          {/* ////////// end price and discount and feature price ///////////// */}
          <ul className="text-main space-y-5 text-lg ">
            {!data.has_auction && hasPrice && (
              <li className="gap-5 ">
                <label className="inline-block min-w-32 font-bold">
                  {t("availableLabel")}:{" "}
                </label>
                <span className="mx-2 text-green-600">
                  {t("available")} {product?.stock || "N/A"}
                </span>
              </li>
            )}
            <li className="gap-5 ">
              <label className="inline-block min-w-32 font-bold">
                {t("brand")}:
              </label>
              <span className="mx-2 text-black inline-block">
                {product?.brand?.name || "N/A"}
              </span>
            </li>
            {categories && (
              <li className="gap-5">
                <label className="inline-block min-w-32 font-bold">
                  {t("categories")}:
                </label>
                <span className="mx-2 text-black inline-block">
                  {categories}
                </span>
              </li>
            )}
          </ul>
          <Separator />
          <div className="mx-auto text-center">
            {!data.has_auction &&
              customFormInputs &&
              hasPrice &&
              Array.isArray(customFormInputs) &&
              customFormInputs?.length > 0 && (
                <p className="font-bold text-xl">{t("complete_form")}</p>
              )}
            {/* is the product on auction or not! */}
            {data?.has_auction ? (
              data?.auction?.ended ? (
                <p className="text-sm font-medium text-red-500 border-red-500 bg-red-50 border p-4 rounded-sm">
                  {s("auctionEnded")}
                </p>
              ) : (
                <AuctionButton auction={data} />
              )
            ) : hasPrice ? (
              <ProductFormComponentRedesignThree
                customFormInputs={customFormInputs}
                product={product}
                loading={loading}
                quantity={quantity}
                addProductToCart={addProductToCart}
                handleIncrement={handleIncrement}
                handleDecrement={handleDecrement}
              />
            ) : null}
          </div>
        </div>
        {/* Images gallery and videos */}
        <Images images={images} videoUrl={videoUrl} />
        {/* Add to Cart and Quantity */}
      </div>
    </div>
  );
}
