"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 { 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 Link from "next/link";
import { useEffect, useState } from "react";
import { IoStar } from "react-icons/io5";
import Images from "./ImagesRedesign";
import ProductFormComponentRedesign from "./ProductFormComponentRedesign";

export default function DetailsRedesign({
  data,
  customFormInputs,
  images,
  videoUrl,
}) {
  const product = data?.product;
  const feature = data?.features?.length > 0 ? data?.features?.[0] : null;
  const [featureIndx, setFeatureIndx] = useState(0);
  const featurePrice = feature?.options?.[featureIndx]?.price;
  const c = useTranslations("cart");
  const t = useTranslations("single-product");
  const {
    addToCart: addToCartLocale,
    incrementQuantity,
    cart: cartLocal,
  } = useCart();
  const { currencyShortname, rate } = useCurrency();
  const [itemExist, setItemExist] = useState(false);

  const locale = useLocale();
  const [quantity, setQuantity] = useState(1);
  const [loading, setLoading] = useState(false);
  const queryClient = useQueryClient();
  const { data: cart, isError } = useQuery({
    queryKey: ["/cart/items", locale],
    queryFu: () =>
      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"] }); // 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">
          {/* Brand  */}
          <Link
            href={`/brands/${product?.brand?.id}`}
            className="text-gray-500 text-xl font-semibold "
          >
            {product?.brand?.name}
          </Link>
          {/* Title */}
          <h2 className="lg:text-4xl md:text-2xl text-xl  max-w-96">
            {product?.title}
          </h2>

          {/* Availability, Reviews */}
          <div className=" rounded-md flex   items-center gap-6 flex-wrap">
            {product.rate && (
              <div className="flex items-center gap-1 justify-center">
                {Array.from({ length: Math.floor(product.rate) }, (_, i) => (
                  <IoStar
                    key={`yellow-${i}`}
                    size={16}
                    className="text-yellow-400"
                  />
                ))}
                {Array.from(
                  { length: 5 - Math.floor(product.rate) },
                  (_, i) => (
                    <IoStar
                      key={`gray-${i}`}
                      size={16}
                      className="text-gray-300"
                    />
                  )
                )}
                <p className="text-sm font-semibold ">
                  {`(${parseFloat(product.rate).toFixed(1)})`}
                </p>
              </div>
            )}
            {/* Reviews */}
            <div className="font-semibold flex items-center gap-1">
              <p>{t("reviews-count")}</p>
              <p className="">{product?.comments?.length}</p>
            </div>
            <div className="font-semibold flex items-center  gap-1 ">
              <p>{t("points")}</p>
              <p className="">{product?.points}</p>
            </div>
            {/* stock */}
            <div className="font-medium border-[1px] border-green-500 text-green-500 rounded-md py-1 px-2 flex items-center  gap-1 ">
              <p
                className={clsx({
                  "text-red-500": Number(product.stock ?? 0) < 4,
                  hidden: product.stock == 0,
                })}
              >
                {t("stock")}: {product.stock}
              </p>
            </div>
          </div>

          {/* Rating */}
          <div className="flex items-center gap-2">
            <p className="text-xl">
              {product?.comments?.length > 0 ? (
                <>
                  {t("rates-count")} : {product?.comments?.length}
                </>
              ) : (
                t("no-rates")
              )}
            </p>
          </div>

          {/* Price */}
          <div className="space-y-3 text-xl lg:text-2xl font-normal">
            <p>
              {t("price")} <span className="">({t("tax-included")})</span>
            </p>
            {/* Main price */}
            <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>
            {/* //////////// */}
            {/* Feature price */}
            {!!featurePrice && (
              <p>
                {t(`price-${feature?.type}`)}:{" "}
                {(Number(featurePrice) * rate).toFixed(2)} {currencyShortname}
              </p>
            )}
            {/* ////////////////// */}
          </div>

          {/* Display Features */}
          <p className="mb-2">{feature?.title}</p>
          {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>
            ))}
          {/* /////////// */}
          <div>
            {customFormInputs &&
              Array.isArray(customFormInputs) &&
              customFormInputs?.length > 0 && (
                <p className="font-bold text-xl">{t("complete_form")}</p>
              )}
            <ProductFormComponentRedesign
              customFormInputs={customFormInputs}
              product={product}
              loading={loading}
              quantity={quantity}
              addProductToCart={addProductToCart}
              handleIncrement={handleIncrement}
              handleDecrement={handleDecrement}
            />
          </div>
        </div>
        {/* Images gallery and videos */}
        <Images images={images} videoUrl={videoUrl} />
        {/* Add to Cart and Quantity */}
      </div>
    </div>
  );
}
