import React, { useEffect } from "react";
import { useState } from "react";
import SliderImage from "@/components/product/sliderImage";
import style from "./productDetail.module.css";
import RelatedProduct from "@/components/product/relatedproduct";
import ProductButtons from "@/components/product/productButtons";
import {
  Favorite,
  FavoriteBorder,
  FavoriteBorderOutlined,
} from "@mui/icons-material";
import { useSelector } from "react-redux";
import { isWishListed } from "@/store/wishlist";
import { useDispatch } from "react-redux";
import { wishlistStoreActions } from "@/store/wishlist";
import { cartStoreActions } from "@/store/cart";
import { useRouter, useNavigate } from "next/router";
import { customerApi } from "@/api/api";
import Loader from "@/components/utils/loader";
import Head from "next/head";
import Image from "next/image";
import Variants from "@/components/variants/variants";
import Reviews from "@/components/reviews/reviews";
import ReactHtmlParser from "react-html-parser";
import ProductQnty from "@/components/product/productQnty";
import FadeInContainer from "@/components/utils/animation/fadeInContainer";
import { accountStoreActions } from "@/store/account";

const ProductDetail = ({ data }) => {
  console.log("dataaa:", data.productData);
  const [productData, setProductData] = useState(data.productData);
  const [loader, setLoader] = useState(false);
  const [image, setImage] = useState(data.image);
  const [selectedQty, setSelectedQty] = useState(1);
  const currencyType = useSelector((state) => state.generalStore.currency_type);
  const router = useRouter();

  const isWishlisted = useSelector(isWishListed(productData._id));
  const account = useSelector((state) => state.accountStore);
  const dispatch = useDispatch();
  const removeWishList = () => {
    dispatch(
      wishlistStoreActions.removeWishList({
        id: productData._id,
        loggedIn: account.loggedIn,
        userid: account.userid,
      })
    );
  };
  const addWishList = () => {
    if (account.loggedIn) {
      dispatch(
        wishlistStoreActions.addWishList({
          product: {
            name: productData.name,
            id: productData._id,
            image:
              productData.image &&
              process.env.NEXT_PUBLIC_UPLOADS +
                "/products/" +
                productData.image[0],
            price_type: productData.price_type,
            price: productData.price,
            qty: selectedQty,
            exactQty: productData.stock,
            offer: productData.offer,
            partNo: productData.partNo,
            tax: productData.tax_rate,
            payment_accepted: productData.payment_accepted,
            brand: productData.category[productData.category.length - 1].name,
          },
          loggedIn: account.loggedIn,
          userid: account.userid,
        })
      );
    } else dispatch(accountStoreActions.openSignInUI({ signInUI: true }));
  };
  const addCart = () => {
    dispatch(
      cartStoreActions.addCart({
        product: {
          name: productData.name,
          id: productData._id,
          image:
            productData.image &&
            process.env.NEXT_PUBLIC_UPLOADS +
              "/products/" +
              productData.image[0],
          price: productData.price,
          price_type: productData.price_type,
          qty: selectedQty,
          exactQty: productData.stock,
          offer: productData.offer,
          tax: productData.tax_rate,
          partNo:
            productData.category[productData.category.length - 1].name || null,
          brand: productData.details.map((item) => {
            if (item.title.toLowerCase() === "part no") return item.value;
          }),
          payment_accepted: productData.payment_accepted,
        },
        loggedIn: account.loggedIn,
        userid: account.userid,
      })
    );
  };

  const getPrice = () => {
    let price = 0;
    if (productData.price_type === "quantity_wise") {
      price = Number(productData.price[0].price);
    } else {
      price = Number(productData.price);
    }
    return price.toFixed(2);
  };
  const getOffer = () => {
    let offer = getPrice() - (productData.offer / 100) * getPrice();
    return offer.toFixed(2);
  };

  const recentViewUpdate = async () => {
    await customerApi
      .post("/recent/customer/view", {
        product_id: productData._id,
      })
      .then((res) => {
        console.log("successfully updated");
      })
      .catch((err) => {
        console.log("err:", err);
      });
  };

  useEffect(() => {
    if (account.loggedIn === true) {
      recentViewUpdate();
    }
  }, [account.loggedIn]);

  useEffect(() => {
    setProductData(data.productData);
    setImage(data.image);
  }, [data]);

  return (
    <React.Fragment>
      <Head>
        <title>
          {`${
            productData.meta_title
              ? productData.meta_title
              : productData.name
                  .replaceAll("<b>", "")
                  .replaceAll("</b>", "")
                  .replaceAll("<i>", "")
                  .replaceAll("</i>", "")
          } - ${process.env.NEXT_PUBLIC_COMPANY_NAME}`}
        </title>
        <meta charset="UTF-8" />
        <meta name="description" content={productData.meta_description} />
        <meta
          name="keywords"
          content={
            productData.meta_keywords.length > 0
              ? productData.meta_keywords.join(",")
              : productData.name
          }
        />
        <meta name="viewport" content="width=device-width, initial-scale=1.0" />
      </Head>
      <FadeInContainer loadVisibile={true}>
        <div className={`${style.product_detail_section} container `}>
          {loader && <Loader className={style.loader} />}
          {!loader && productData.name && (
            <div className={style.custom_grid}>
              <div className={style.slider}>
                <div className="sticky-top">
                  <div className={`${style.image_section}`}>
                    <SliderImage images={image} />
                  </div>
                </div>
              </div>

              <div className={style.detail_section}>
                {productData.category.length > 0 &&
                  productData.category[Number(productData.category.length - 1)]
                    .name && (
                    <div className={style.brand}>
                      {productData.details.map((item) => {
                        item.name.toLowerCase() === "brand" && item.name;
                      })}
                    </div>
                  )}
                <div className={style.product_name}>
                  <h1>{ReactHtmlParser(productData.name)}</h1>
                </div>
                {getPrice() > 0 && (
                  <>
                    <div
                      className={`${style.price_section} ${
                        productData.stock == 0 && style.no_price
                      }`}
                    >
                      {productData.stock > 0 || productData.stock === -1 ? (
                        getPrice() && productData.offer ? (
                          <>
                            <div className={style.price}>
                              {getOffer()}
                              &nbsp;{currencyType}
                            </div>
                            <div className={style.prev_price}>
                              {getPrice()}
                              &nbsp;{currencyType}
                            </div>
                            {productData.offer && (
                              <div className={style.offer}>
                                ( {productData.offer}% Off )
                              </div>
                            )}
                          </>
                        ) : (
                          <div className={style.price}>
                            {getPrice()}
                            &nbsp;{currencyType}
                          </div>
                        )
                      ) : (
                        <div className={style.out_of_stock}>Out Of Stock</div>
                      )}
                    </div>
                    {productData.price_type === "quantity_wise" && (
                      <div className={style.quantity_price_section}>
                        <div className={style.quantity_price}>
                          {productData.price.map((item, index) => (
                            <div key={item.price}>
                              {productData.price.length - 1 != index
                                ? `Less Than Or Equal ${item.quantity} Quantity, ${item.price} ${currencyType}`
                                : `Above ${item.price} ${currencyType}`}
                            </div>
                          ))}
                        </div>
                      </div>
                    )}
                  </>
                )}
                <ProductButtons productData={productData} />
                <Variants
                  product_id={productData._id}
                  variants={productData.variants}
                  className={style.varient_section}
                />

                {productData.details.length > 0 && (
                  <div className={style.specifications}>
                    <div className={style.product_page_title}>Details</div>
                    <table>
                      <tbody>
                        {productData.details.map(
                          (item, index) =>
                            item.value && (
                              <tr key={item.title}>
                                <td className={style.speciHead}>
                                  {item.title}
                                </td>
                                {item.value !== "null" && item.value && (
                                  <td>{item.value}</td>
                                )}
                              </tr>
                            )
                        )}
                      </tbody>
                    </table>
                  </div>
                )}
                {productData.description &&
                  productData.description.replace("<p><br></p>", "") && (
                    <div className={style.description_section}>
                      <div className={style.product_page_title}>
                        About this item
                      </div>
                      <div className={`${style.product_description} ql-editor`}>
                        {ReactHtmlParser(productData.description)}
                      </div>
                    </div>
                  )}
              </div>
            </div>
          )}

          <Reviews
            product_id={productData._id}
            product_code={productData.product_code}
            className={style.review_section}
          />
          <div className={style.related_product_section}>
            <RelatedProduct
              id={
                productData.category &&
                productData.category.length > 0 && [
                  productData.category[productData.category.length - 1]
                    .category,
                ]
              }
            />
          </div>
        </div>
      </FadeInContainer>
    </React.Fragment>
  );
};

export default ProductDetail;

export const getServerSideProps = async (ctx) => {
  let productData = {};
  if (!ctx.query.id || ctx.query.id === "undefined")
    return {
      redirect: {
        destination: "/store",
        permanent: false,
      },
    };
  const id = ctx.query.id;
  const type = ctx.query.type;
  await customerApi
    .get(`/product?${type === "id" ? "_id=" : "slug="}${id}`)
    .then((res) => {
      console.log("res.data.data.result: ", res.data.data.result);
      if (!res.data.data || !res.data.data.result)
        return {
          redirect: {
            destination: "/store",
            permanent: false,
          },
        };
      let newArray = { ...res.data.data.result };
      if (newArray.details.length > 0) {
        for (const innerItem of newArray.details) {
          if (innerItem.title.toLowerCase() === "part no") {
            newArray["partNo"] = innerItem.value;
          }
        }
      }
      productData = newArray;
    })
    .catch((err) => {
      console.log(err);
      return {
        redirect: {
          destination: "/store",
          permanent: false,
        },
      };
    });
  let image = [];
  if (productData.image && productData.image.length > 0) {
    let newArray = [];
    for (const item of productData.image) {
      newArray.push({
        image: process.env.NEXT_PUBLIC_UPLOADS + "/products/" + item,
      });
    }
    image = newArray;
  }
  return {
    props: {
      data: {
        productData: productData,
        image: image,
      },
    },
  };
};
