"use client";
import { useEffect, useState } from "react";
import Image from "next/image";
import axios from "@/utils/axios-config";
import Link from "next/link";
import { Button, message, Pagination, Tooltip } from "antd";
import { useTranslations, useLocale } from "next-intl";
import { useDispatch, useSelector } from "react-redux";
import { useMutation } from "@tanstack/react-query";
import { CgShoppingCart } from "react-icons/cg";
import { saveProduct } from "@/store/product/actions";
import { fetchCartLength, fetchFavouritesLength } from "@/store/cart/actions";
import { IoMdHeart, IoMdHeartEmpty } from "react-icons/io";
import ProductSkeleton from "@/components/skeletons/skeleton";
import Product from "@/components/product/product";
import NoItem from "@/components/no-items";

interface Product {
  offer_price(offer_price: any): unknown;
  id: number;
  product_id: number;
  product_name: string;
  product_image: string;
  product_brand_name: string;
  product_price: string;
  product_offer_price: string;
  offer_title: string;
  offer_discount_value: number;
  offer_discount_type: number;
  is_cart: number;
  is_favourite: number;
  rate_avg: string;
  rate_count: number;
  product_offer_id: any;
}

export default function FavoritesPage() {
  const [favorites, setFavorites] = useState<Product[]>([]);
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState<string>("");
  const [hoveredItemId, setHoveredItemId] = useState<any>(undefined);
  const [productHover, setProductHover] = useState(false);
  const [productFavHover, setProductFavHover] = useState(false);
  const [cartProducts, setCartProducts] = useState<any>([]);
  const [productId, setProductId] = useState<undefined | number>(undefined);
  const dispatch = useDispatch();
  const [favouritesProducts, setFavouritesProducts] = useState<any>([]);
  const [favouriteLoading, setFavouriteLoading] = useState(false);
  const t = useTranslations();
  const { idToken } = useSelector((state: { Auth: any }) => state.Auth);
  const { cartLength } = useSelector((state: { Cart: any }) => state.Cart);
  const locale = useLocale();
  const { searchValue } = useSelector((state: { Search: any }) => state.Search);
  const [pagination, setPagination] = useState({
    pageSize: 20,
    totalCount: 0,
    currentPage: 0,
  });
  useEffect(() => {
    setPagination({ pageSize: 20, totalCount: 0, currentPage: 0 });
    //fetchProductsData()
  }, [searchValue]);
  const fetchFavorites = async () => {
    const params: { [key: string]: string | number } = {};
    if (typeof pagination.currentPage === "number") {
      params.skip = pagination.currentPage * pagination.pageSize;
      params.take = pagination.pageSize;
    }
    try {
      const response = await axios.get(
        `/favorites?skip=${params?.skip}&take=${params?.take}`
      );
      // console.log("Favouritesresponse", response?.data);
      setPagination((current) => ({
        ...current,
        totalCount: response?.data?.count,
      }));
      if (response?.data?.status) {
        const favList = response.data.data.map((item: any) => ({
          id: item.id,
          product_id: item?.product_id,
          product_name: item?.product_name,
          product_image: item?.product_image,
          product_brand_name: item?.product_brand_name,
          offer_discount_value: item?.offer_discount_value,
          offer_discount_type: item?.offer_discount_type,
          offer_buy_quantity: item?.offer_buy_quantity,
          offer_free_quantity: item?.offer_free_quantity,
          Product_requires_prescription: item?.Product_requires_prescription,
          product_price: item?.product_price,
          offer_price: item?.offer_price,
          offer_title: item?.offer_title,
          is_favourite: 1,
          is_cart: item?.is_cart,
          product_offer_id: item?.product_offer_id,
        }));

        setFavorites(favList);
        console.log("FavList", favList);
        dispatch(fetchFavouritesLength(favList?.length));
      }
    } catch (error) {
      console.error("Failed to fetch favorites:", error);
      setError("Failed to load favorites. Please try again.");
    } finally {
      setLoading(false);
    }
  };
  useEffect(() => {
    if (idToken) {
      fetchFavorites();
    }
  }, [pagination?.currentPage, pagination?.pageSize]);
  useEffect(() => {
    const arr = [];
    //  console.log("products", products);
    for (let i = 0; i <= favorites?.length; i++) {
      if (favorites[i]?.is_cart) {
        arr.push(favorites[i]?.product_id);
      }
      setCartProducts([...arr]);
    }
  }, [favorites]);
  /// add product to cart
  const mutation = useMutation({
    mutationFn: (values: any) =>
      axios["post"]("/add-to-cart", values, {
        // headers: {
        //   "Accept-Language": `${locale === "en" ? "en-US" : "ar-SA"}`,
        // },
      }),
    onSuccess: (res: any) => {
      // console.log(res.data);

      dispatch(fetchCartLength(cartLength + 1));
      message.success(res.data.message);
      setCartProducts([...cartProducts, productId]);
    },
    onError: (err: any) => {
      const {
        status,
        data: { message },
      } = (err as any).response;

      message.error(message, {
        position: "top-center",
        duration: 5000,
      });
    },
  });
  const addToCartFunc = (item: Product) => {
    setProductId(item?.product_id);
    //console.log("product", item);
    mutation.mutate({
      product_id: item.product_id,
      offer_id: item?.product_offer_id,
      quantity: 1,
    });
  };
  const toggleFavorite = async (item: any) => {
    try {
      setFavouriteLoading(true);
      const response = await axios.post("/favorites", {
        product_id: item,
      });

      message.success(response?.data?.message);

      fetchFavorites();
    } catch (error: any) {
      message.error(error?.message);
    } finally {
      setFavouriteLoading(false);
    }
  };

  const offerDiscreption = (
    buyQuantity: number,
    freeQuantity: number,
    discountType: number,
    discountValue: number
  ) => {
    return (
      <>
        {freeQuantity === 0 ? (
          <div
            className={`${
              locale === "en" ? "flex-row-reverse" : "flex-row"
            } flex items-center`}
          >
            <span className={`${locale === "en" ? "ms-2" : "me-2"}`}>
              {t("off")}{" "}
            </span>

            {discountValue}
            {discountType === 1 ? (
              <Image
                src={"/images/ryial.svg"}
                alt="currancy icon"
                width={12}
                height={12}
                className="ms-1"
              />
            ) : (
              "%"
            )}
          </div>
        ) : discountValue === 100 && discountType === 2 ? (
          ` ${buyQuantity} + ${freeQuantity} ${t("for-free")}`
        ) : (
          <>
            {/* {t("buy")} {buyQuantity} + {freeQuantity} {t("and-get")} */}
            <>
              {" "}
              <span className="ps-[2px]">{discountValue}</span>
              {discountType === 1 ? (
                <Image
                  src={"/images/currancy-white.svg"}
                  alt="currency icon"
                  width={15}
                  height={15}
                  className="inline"
                />
              ) : (
                "%"
              )}{" "}
              {Number(buyQuantity) === 1
                ? t("off-on-second-item")
                : t("off-on-third-item")}
            </>
          </>
        )}
      </>
    );
  };

   const offerCalcLabel = (
    price: number,
    buyQuantity: number,
    freeQuantity: number,
    discountType: number,
    discountValue: number
  ) => {
    return (
      <div className="flex items-center">
      <span className="me-1  text-[12px]">{t("offer-price")}</span>
        {freeQuantity === 0 ? (
          <></>
        ) : discountValue === 100 && discountType === 2 ? (
          // ` ${buyQuantity} + ${freeQuantity} ${t("for-free")}`
          <div className="flex items-center gap-1">
            <p className="text-white">{(Number(buyQuantity) * Number(price)).toFixed(2)}</p>
            <p className="text-white opacity-70 line-through">
              {((Number(buyQuantity) + Number(freeQuantity)) * Number(price)).toFixed(2)}
            </p>
          </div>
        ) : (
          <>
            {/* {t("buy")} {buyQuantity} + {freeQuantity} {t("and-get")} */}
            <>
              {/* {" "}
              <span className="ps-[2px]">{discountValue}</span>
              {discountType === 1 ? (
                <Image
                  src={"/images/currancy-white.svg"}
                  alt="currency icon"
                  width={15}
                  height={15}
                  className="inline"
                />
              ) : (
                "%"
              )}{" "}
              {Number(buyQuantity) === 1
                ? t("off-on-second-item")
                : t("off-on-third-item")} */}
              <div className="flex items-center gap-1">
                <p className="text-white">
                  {(Number(discountType) === 1
                    ? Number(buyQuantity) * Number(price) +
                      Number(freeQuantity) *
                        (Number(price) - Number(discountValue))
                    : (Number(buyQuantity) * Number(price)) +
                      Number(freeQuantity) *
                        ((Number(price) / 100) * (100-Number(discountValue)))).toFixed(2)}
                </p>
                <p className="text-white opacity-70 line-through">
                  {((Number(freeQuantity) + Number(buyQuantity)) * Number(price)).toFixed(2)}
                </p>
              </div>
            </>
          </>
        )}
      </div>
    );
  };

  if (loading) {
    return (
      <div className="container mx-auto    pt-[2rem] text-center">
        <ProductSkeleton />
      </div>
    );
  }

  return (
    <div className="container mx-auto    pt-[2rem]">
      <h1 className="text-[#184363] text-[25px] sm:text-3xl md:text-3xl font-bold mb-4 sm:mb-6 text-center pt-[50px] pb-[20px]">
        {t("my-favourites")}
      </h1>
      {error ? (
        <p className="text-red-500 text-center">{error}</p>
      ) : favorites.length > 0 ? (
        <div className="flex flex-wrap justify-center gap-6">
          {favorites.map((item: any) => (
            <div
              key={item.id}
              className="w-[220px] flex flex-col justify-between  border rounded-lg shadow-md overflow-hidden"
              onClick={() => {
                // console.log('aaaaaaaaa')
                dispatch(
                  saveProduct({
                    id: item.product_id,
                    name: item.product_name,
                    image: item.product_image,
                    brand_name: item.product_brand_name,
                    price: item.product_price,
                    offer_price: item.offer_price,
                    offer_title: item.offer_title,
                    Product_requires_prescription:
                      item.Product_requires_prescription,
                    is_favourite: 1,
                    offer_discount_value: item?.offer_discount_value,
                    offer_discount_type: item?.offer_discount_type,
                    offer_free_quantity: item?.offer_free_quantity,
                    offer_buy_quantity: item?.offer_buy_quantity,
                    is_cart: item.is_cart,
                    rate_avg: item.rate_avg,
                    rate_count: item.rate_count,
                  })
                );
              }}
            >
              <div className="w-full">
                <div
                  className="relative aspect-[1/1]  p-2"
                  onMouseOver={(e) => {
                    setProductHover(true);

                    setHoveredItemId(item?.product_id);
                  }}
                  onMouseLeave={() => {
                    setHoveredItemId("");
                    setProductHover(false);
                  }}
                >
                  <Link
                    href={`/${locale}/products/${(item?.product_name)
                      .replace(/[^a-zA-Z0-9\u0600-\u06FF]+/g, "-")
                      .replace(/^-+|-+$/g, "")
                      .toLowerCase()}?id=${item?.product_id}`}
                    locale={false}
                    className="absolute w-full  h-full top-0 left-0 z-[40] "
                  ></Link>
                  {/* {
                    <span className="absolute z-[40] bg-red-500 text-white rounded-full text-xs top-[9px] left-[9px] py-1 px-3 text-wrap max-w-[90%] ">
                      aaaaaaaa
                    </span>
                  } */}

                  {item?.offer_title && (
                    <p className="absolute z-[50] flex gap-2 items-center justify-center w-fit bg-red-500 text-white py-1 text-sm top-[0px] start-[0px]  px-3 text-wrap opacity-80 ">
                    
                      {offerDiscreption(
                        item?.offer_buy_quantity,
                        item?.offer_free_quantity,
                        item?.offer_discount_type,
                        item?.offer_discount_value
                      )}
                    </p>
                  )}
                  {/* <img
                    src={item.product_image[0] || "/default-image.png"}
                    alt={item.product_name}
                    // fill
                    className="object-cover w-full h-full"
                  /> */}
                  <Image
                    src={item.product_image[0] || "/default-image.png"}
                    fill
                    sizes="100vw"
                    loading="lazy"
                    alt=""
                  />
                  {productHover && hoveredItemId === item.product_id && (
                    <>
                      <div className="absolute top-0 left-0 h-full w-full bg-[#F6F5FA] opacity-50 z-[20]"></div>

                      <div className="absolute top-0 left-0 w-full h-full flex justify-center items-center">
                        <div
                          className={`cursor-pointer ${
                            !favouriteLoading
                              ? "pointer-events-auto opacity-100"
                              : "pointer-events-none opacity-35"
                          } p-3 m-1 rounded-[50%] bg-[#EDF4F6] flex justify-center items-center z-[50]`}
                          onMouseOver={() => setProductFavHover(true)}
                          onMouseLeave={() => setProductFavHover(false)}
                          onClick={() => toggleFavorite(item?.product_id)}
                        >
                          {productFavHover ||
                          favorites?.filter(
                            (ele: any) => ele.product_id === item?.product_id
                          ).length > 0 ? (
                            <IoMdHeart className=" text-[30px] text-red-600" />
                          ) : (
                            <IoMdHeartEmpty className="text-[30px]" />
                          )}
                        </div>
                      </div>
                    </>
                  )}
                  {item?.Product_requires_prescription === 1 && (
                    <div
                      className={`absolute bottom-0 ${
                        locale === "ar"
                          ? "right-0 rounded-[2px] "
                          : "left-0 rounded-[2px]"
                      } flex items-center justify-center  gap-1 px-2 py-1 opacity-80 w-fit h-fit bg-[#FBC43A] text-white `}
                    >
                      <Image
                        src={"/images/prescription-icon.svg"}
                        alt="prescription icon"
                        width={18}
                        height={18}
                      />
                      <p className="text-[12px]">{t("prescription")}</p>
                    </div>
                  )}
                </div>
                <div className=" px-4 py-4 flex flex-col ">
                  {/* <p className="text-third text-[18px] font-semibold">
                  {item.product_name}
                </p> */}
                  <Tooltip title={item?.product_name} color="rgba(3,184,158,0.6)" overlayInnerStyle={{ fontSize: 12, padding: "4px 8px" }}>
                    <Link
                      href={`${locale}/products/${(item?.product_name)
                        .replace(/[^a-zA-Z0-9\u0600-\u06FF]+/g, "-")
                        .replace(/^-+|-+$/g, "")
                        .toLowerCase()}?id=${item?.product_id}`}
                      locale={false}
                      className="md:p-1 text-productNameColor max-w-[230px] block overflow-hidden text-ellipsis whitespace-nowrap font-sans max-[500px]:text-center mt-2"
                    >
                      {item?.product_name}
                    </Link>
                  </Tooltip>
                  <div className="flex justify-between items-center">
                    <p className="text-secondary text-[16px]">
                      {item.product_brand_name}
                    </p>
                    <div
                      className="p-3 rounded-full cursor-pointer bg-gray-200 flex items-center justify-center"
                      onClick={() => toggleFavorite(item.product_id)}
                    >
                      {item.is_favourite ? (
                        <IoMdHeart className="text-red-600 text-xl" />
                      ) : (
                        <IoMdHeartEmpty className="text-xl" />
                      )}
                    </div>
                  </div>
                  <div className="flex items-center py-2">
                    {Number(item.product_offer_price) > 0 &&
                    Number(item.product_offer_price) <
                      Number(item.product_price) ? (
                      <p className="text-secondary text-[18px] font-bold me-2">
                        {item.product_offer_price}{" "}
                        <sup className="inline-block">
                          <Image
                            src={"/images/ryial.svg"}
                            alt="currancy icon"
                            width={12}
                            height={12}
                            className="ms-1"
                          />
                        </sup>
                      </p>
                    ) : null}
                    <p
                      className={`${
                        Number(item?.product_offer_price) > 0 &&
                        Number(item.product_offer_price) <
                          Number(item.product_price)
                          ? "line-through text-gray-400 "
                          : "text-secondary"
                      }text-md flex`}
                    >
                      {item.product_price}{" "}
                      {/* <sup className=" inline-block"> */}
                        <Image
                          src={"/images/ryial.svg"}
                          alt="currancy icon"
                          width={12}
                          height={12}
                          className="ms-1"
                        />
                      {/* </sup> */}
                    </p>
                  </div>
                </div>
                {
                 Number(item?.offer_free_quantity) > 0 ? (
                  <div className=" w-fit bg-primary bg-opacity-50 px-2  rounded-e-[5px]">
                    {offerCalcLabel(
                      item?.product_price,
                      item?.offer_buy_quantity,
                      item?.offer_free_quantity,
                      item?.offer_discount_type,
                      item?.offer_discount_value
                    )}
                  </div>
                 ) : null
                }
              </div>
              <div className="w-full px-4 pb-4">
                <Button
                  className={`rounded-[72px] ${
                    cartProducts?.filter((ele: any) => ele === item?.product_id)
                      .length > 0
                      ? "!text-primary"
                      : "!text-secondary"
                  } mt-4 min-h-[40px] !border-none !outline-none bg-[#EDF4F6] p-4 w-full hover:!bg-[#EDF4F6]`}
                  onClick={() => {
                    addToCartFunc(item);
                  }}
                  loading={productId === item?.product_id && mutation.isPending}
                >
                  <CgShoppingCart className="text-xl" />
                  {cartProducts?.filter((ele: any) => ele === item?.product_id)
                    .length > 0
                    ? t("added-to-cart")
                    : t("add-to-cart")}
                </Button>
              </div>
            </div>
          ))}
        </div>
      ) : (
        <NoItem />

        // <p className="text-gray-500 text-center">No favorites found.</p>
      )}
      {favorites?.length > 0 && (
        <Pagination
          //defaultCurrent={1}

          total={pagination.totalCount}
          current={pagination.currentPage + 1}
          pageSize={pagination.pageSize}
          locale={{ items_per_page: `/${t("page")}` }}
          showSizeChanger
          onChange={(page, pageSize) => {
            setPagination((current) => ({
              ...current,
              pageSize,
              currentPage: page - 1,
            }));
          }}
          className={locale === "ar" ? "rtl-pagination" : ""}
        />
      )}
    </div>
  );
}
