"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 FallbackImage from "@/app/ui/shared/FallbackImage";
import { RadioGroup, RadioGroupItem } from "@/components/ui/radio-group";
import { toastError, toastSuccess } from "@/services/custom-toast";
import useCart from "@/stores/cart";
import { useCurrency } from "@/stores/currency-state";
import clsx from "clsx";
import { useLocale, useTranslations } from "next-intl";
import Link from "next/link";
import { useEffect, useState } from "react";
import ProductFormComponent from "../VendorUi/ProductForm/ProductFormComponent";
import Images from "./Images";
import { useQueryClient } from "@tanstack/react-query";

export default function Details({ 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 queryClient = useQueryClient();
  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);

  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;
      }

      const { data, error, message } = await fetchData({
        endPoint: "/cart/items",
        token,
        locale,
      });

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

    fetchCart();
  }, [product.id, cartLocal, locale]);

  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"] }); // Update cart state
    } 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">
          {/* Title */}
          <h2 className="lg:text-3xl md:text-2xl text-xl font-semibold max-w-96">
            {product?.title}
          </h2>

          {/* Category, Availability, Reviews */}
          <div className="bg-white p-6 rounded-md flex items-center gap-6 flex-wrap">
            {/* Category */}
            <div className="flex items-center gap-2">
              <FallbackImage
                src={product?.brand?.image}
                placeholderSrc={"/brands/xiaomi.svg"}
                width={25}
                height={25}
                alt={product?.brand?.name}
              />
              <Link
                href={`/brands/${product?.brand?.id}`}
                className="text-main font-semibold underline underline-offset-1"
              >
                {product?.brand?.name}
              </Link>
            </div>

            {/* Availability */}
            <div className="font-semibold flex items-center gap-1 underline underline-offset-2">
              <p>{t("available")}</p>
              <p className={"text-main"}>{product?.stock}</p>
            </div>

            {/* Reviews */}
            <div className="font-semibold flex items-center gap-1 underline underline-offset-2">
              <p>{t("reviews-count")}</p>
              <p className="text-main">{product?.comments?.length}</p>
            </div>
            <div className="font-semibold flex items-center gap-1 underline underline-offset-2">
              <p>{t("points")}</p>
              <p className="text-main">{product?.points}</p>
            </div>
          </div>

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

          {/* Price */}
          <div className="space-y-2 font-normal">
            <p
              className={clsx({
                "text-red-500": Number(product.stock ?? 0) < 4,
                hidden: product.stock == 0,
              })}
            >
              {t("stock")}: {product.stock}
            </p>
            <p>
              {t("price")}{" "}
              <span className="text-xs">({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>
        {/* Images gallery and videos */}
        <Images images={images} videoUrl={videoUrl} />
        {/* Add to Cart and Quantity */}
      </div>
      <div className="">
        {customFormInputs &&
          Array.isArray(customFormInputs) &&
          customFormInputs?.length > 0 && (
            <p className="font-bold text-xl">{t("complete_form")}</p>
          )}
        <ProductFormComponent
          customFormInputs={customFormInputs}
          product={product}
          loading={loading}
          quantity={quantity}
          addProductToCart={addProductToCart}
          handleIncrement={handleIncrement}
          handleDecrement={handleDecrement}
        />
      </div>
    </div>
  );
}
