import style from "./header.module.css";
import Image from "next/image";
import ProductSearch from "@/components/utils/productSearch";
import { useEffect, useLayoutEffect, useMemo, useRef, useState } from "react";
import { CancelToken } from "axios";
import { useRouter } from "next/router";
import Navbar from "@/layouts/navbar";
import { PiShoppingCartLight } from "react-icons/pi";
import { PiHeartLight } from "react-icons/pi";
import { PiUserLight } from "react-icons/pi";
import { GoSearch } from "react-icons/go";
import { useWindowSize } from "@/customHook/useWindowSize";
import Cart from "@/components/cart/cart";
import WishList from "@/components/wishlist/wishlist";
import { useSelector } from "react-redux";
import { getCartTotalPrice, getCartTotalCount } from "@/store/cart";
import { getWishListTotalCount, wishlistStoreActions } from "@/store/wishlist";
import Account from "@/components/layouts/header/account";
import { customerApi, authApi } from "@/api/api";
import Loader from "@/components/utils/loader";
import { useDispatch } from "react-redux";
import { cartStoreActions } from "@/store/cart";
import { accountStoreActions } from "@/store/account";
import NextImage from "@/other/NextImage";
import Message from "@/components/layouts/header/message";
import PopupMessage from "@/components/popupMessage/popupMessage";
import { usePathname } from "next/navigation";
import {
  EmailOutlined,
  LocationOnOutlined,
  PhoneOutlined,
  PhoneAndroidOutlined,
  FacebookOutlined,
  Instagram,
  YouTube,
  WhatsApp,
} from "@mui/icons-material";
import { IoCloseOutline } from "react-icons/io5";

import X from "@mui/icons-material/X";

const Header = (props) => {
  const { width } = useWindowSize();
  const cartLoader = useSelector((state) => state.cartStore.cartLoader);
  const currencyType = useSelector((state) => state.generalStore.currency_type);
  const wishlistLoader = useSelector(
    (state) => state.wishlistStore.wishlistLoader
  );
  const [customerSelectOptions, setCustomerSelectOptions] = useState([]);
  const [searchLoader, setSearchLoader] = useState(false);
  let timer;
  const totalPrice = useSelector(getCartTotalPrice);
  const dispatch = useDispatch();
  const source = CancelToken.source();
  const router = useRouter();
  const [topMenu, setTopMenu] = useState(true);
  const [cartOpen, setCartOpen] = useState(false);
  const [favoriteOpen, setFavoriteOpen] = useState(false);
  const cartCount = useSelector(getCartTotalCount);
  const favoriteCount = useSelector(getWishListTotalCount);
  const account = useSelector((state) => state.accountStore);
  const [searchOpen, setSearchOpen] = useState(true);
  const [height, setHeight] = useState(0);
  const ref = useRef(null);
  const hitRef = useRef();
  const siteLogo = useSelector((state) => state.generalStore.site_logo);
  const socialMedia = useSelector((state) => state.generalStore.social_media);
  const [topClose, setTopClose] = useState(false);
  const [topLoader, setTopLoader] = useState(true);
  const path = usePathname();
  const [searchHide, setSearchHide] = useState(true);

  // useEffect(() => {
  //   if (!ref.current) return;
  //   if (path === "/") {
  //     const observer = new IntersectionObserver((entries) => {
  //       entries.forEach((entry) => {
  //         const target = entry.target;
  //         console.log("entry.isIntersecting", entry.target);

  //         if (entry.isIntersecting) {
  //           ref.current.style.backgroundColor = "transparent";
  //           ref.current.style.position = "fixed";
  //           ref.current.style.borderColor = "transparent";
  //         } else {
  //           ref.current.style.backgroundColor = "var(--primary)";
  //           ref.current.style.position = "fixed";
  //           ref.current.style.borderColor = "rgba(0,0,0,0.1)";
  //         }
  //       });
  //     });

  //     observer.observe(hitRef.current);

  //     return () => {
  //       observer.disconnect();
  //     }; // clean up
  //   } else {
  //     ref.current.style.backgroundColor = "var(--primary)";
  //     ref.current.style.position = "sticky";
  //     ref.current.style.borderColor = "rgba(0,0,0,0.1)";
  //   }
  // }, [ref.current, path]);

  useMemo(() => {
    if (width > 768) {
      setSearchOpen(true);
    } else if (width <= 768) {
      setSearchOpen(false);
    }

    if (width <= 768) {
      setTopMenu(false);
    } else {
      setTopMenu(true);
    }
  }, [width]);

  useEffect(() => {
    if (Object.keys(props.accountData).length > 0) {
      if (props.accountData.success === true)
        dispatch(
          accountStoreActions.updateLoggedIn({
            loggedIn: true,
            name: props.accountData.name,
            image: props.accountData.image,
            userid: props.accountData._id,
          })
        );
    }
  }, [props.accountData]);

  const searchProducts = async (value = "") => {
    setSearchLoader(true);
    clearTimeout(timer);
    timer = setTimeout(async () => {
      await customerApi
        .get("/search/products?search=" + value, {
          cancelToken: source.token,
        })
        .then((res) => {
          setCustomerSelectOptions(() => {
            let newArray = [];
            if (res.data.data.length > 0) {
              for (const item of res.data.data) {
                let partNo = null;

                if (item.details)
                  for (const innerItem of item.details) {
                    if (innerItem.title.toLowerCase() === "part no") {
                      partNo = innerItem.value;
                    }
                  }
                newArray.push({
                  title: item.name,
                  partNo: partNo,
                  id: item._id,
                  image:
                    item.image && item.image.length > 0 ? item.image[0] : null,
                  brand:
                    item.category && item.category.length > 0
                      ? item.category[Number(item.category.length - 1)].name
                      : null,
                });
              }
              return newArray;
            }
          });
          setSearchLoader(false);
        })
        .catch((err) => {
          console.log(err);
          setSearchLoader(false);
        });
    }, 500);
  };

  const onOpenWishList = () => {
    if (account.loggedIn) setFavoriteOpen(true);
    else dispatch(accountStoreActions.openSignInUI({ signInUI: true }));
  };

  // For fixed menu

  // useEffect(() => {
  //   if (!ref.current) return;
  //   const observer = new IntersectionObserver((entries) => {
  //     entries.forEach((entry) => {
  //       const target = entry.target;
  //       if (topMenu === true) {
  //         if (entry.isIntersecting) {
  //           ref.current.style.position = "absolute";
  //           ref.current.style.background = "transparent";
  //           ref.current.style.top = "auto";
  //           ref.current.style.border = "none";
  //         } else {
  //           ref.current.style.position = "fixed";
  //           ref.current.style.top = 0;
  //           ref.current.style.background = "rgba(255, 255, 255, 1)";
  //           ref.current.style.border = "1px solid rgba(0,0,0,0.1)";
  //         }
  //       } else {
  //         if (entry.isIntersecting) {
  //           ref.current.style.position = "relative";
  //           ref.current.style.background = "rgba(255, 255, 255, 1)";
  //           ref.current.style.top = "auto";
  //           ref.current.style.border = "1px solid rgba(0,0,0,0.1)";
  //         } else {
  //           ref.current.style.position = "sticky";
  //           ref.current.style.top = 0;
  //           ref.current.style.background = "rgba(255, 255, 255, 1)";
  //           ref.current.style.border = "1px solid rgba(0,0,0,0.1)";
  //         }
  //       }
  //     });
  //   });
  //   if (path !== "/") {
  //     ref.current.style.position = "sticky";
  //     ref.current.style.top = 0;
  //     ref.current.style.background = "rgba(255, 255, 255, 1)";
  //     ref.current.style.border = "1px solid rgba(0,0,0,0.1)";
  //     observer.disconnect();
  //   } else {
  //     console.log("path: ", path);
  //     observer.observe(hitRef.current);
  //   }

  //   return () => {
  //     observer.disconnect();
  //   }; // clean up}
  // }, [ref.current, path, topMenu]);

  return (
    <>
      <PopupMessage />
      {/* {!topMenu && <div style={{ height: `${height}px` }}></div>} */}

      {!topClose && (
        <div className={style.top_header} ref={hitRef}>
          <div className={style.social_network}>
            {!topLoader &&
              Object.keys(socialMedia).length > 0 &&
              (socialMedia.facebook ||
                socialMedia.instagram ||
                socialMedia.twitter ||
                socialMedia.youtube) && (
                <>
                  <div className={style.text}>Follow</div>
                  <div className={style.social_icon}>
                    {socialMedia.facebook && (
                      <a href={socialMedia.facebook}>
                        <FacebookOutlined />
                      </a>
                    )}
                    {socialMedia.instagram && (
                      <a href={socialMedia.instagram}>
                        <Instagram />
                      </a>
                    )}
                    {socialMedia.x && (
                      <a href={socialMedia.x}>
                        <X />
                      </a>
                    )}
                    {socialMedia.whatsapp && (
                      <a href={socialMedia.whatsapp}>
                        <WhatsApp />
                      </a>
                    )}
                    {socialMedia.youtube && (
                      <a href={socialMedia.youtube}>
                        <YouTube />
                      </a>
                    )}
                  </div>
                </>
              )}
          </div>
          <Message
            close={() => setTopClose(true)}
            loader={(value) => setTopLoader(value)}
          />
          <div className={style.buttons}>
            {!topLoader && (
              <button
                type="button"
                className="secondary-btn"
                onClick={() => router.push("/become-a-seller")}
              >
                Become A Seller
              </button>
            )}
          </div>
        </div>
      )}

      <div className={style.header} ref={ref}>
        <div className="container-fluid">
          <div className={style.grid_header}>
            <div className={style.menu_option}>
              <Navbar />
              {searchOpen && (
                <div
                  className={style.search_section}
                  // onMouseEnter={() =>
                  //   searchHide && setSearchOpen((prev) => !prev)
                  // }
                  // onMouseLeave={() =>
                  //   searchHide && setSearchOpen((prev) => !prev)
                  // }
                >
                  <div className={style.search_box_class}>
                    <div
                      className={`${style.search_bar} ${
                        searchOpen ? style.openSearch : ""
                      }`}
                    >
                      {searchOpen && (
                        <div className={style.productSearchClass}>
                          <ProductSearch
                            setOption={customerSelectOptions}
                            placeholder={`I'm shopping for...`}
                            setSearchPlaceholder={"Search Customer"}
                            closeSearch={() => setSearchOpen(false)}
                            getValue={(value) => {
                              setCustomerSelectOptions([]);
                              // searchProducts();
                            }}
                            setValue={""}
                            loader={searchLoader}
                            searchData={searchProducts}
                            customCss={`${style.custom_css_select}`}
                          />
                        </div>
                      )}
                    </div>
                    <div
                      className={`${style.search_icon} ${
                        searchOpen ? style.selected : ""
                      }`}
                    >
                      <GoSearch />
                    </div>
                    <div
                      className={`${style.cancel_icon} ${
                        searchOpen ? style.selected : ""
                      }`}
                      onClick={() => setSearchOpen(false)}
                    >
                      <IoCloseOutline />
                    </div>
                  </div>
                </div>
              )}
            </div>
            <div className={style.header_top_section}>
              <div className={style.logo} onClick={() => router.push("/")}>
                <NextImage
                  src={
                    process.env.NEXT_PUBLIC_UPLOADS + "/settings/" + siteLogo
                  }
                  alt="Logo"
                />
              </div>
            </div>

            <div className={style.site_option}>
              <div className={style.menu_flex}>
                {!topMenu && (
                  <div
                    className={style.site_option_section}
                    onClick={() => setSearchOpen(true)}
                  >
                    <div className={style.icon}>
                      <GoSearch />
                    </div>
                  </div>
                )}
                {topMenu && (
                  <>
                    {account.loggedIn ? (
                      <div
                        className={style.site_option_section}
                        onClick={() => router.push("/account")}
                      >
                        {account.img ? (
                          <div className={style.profile_image}>
                            <NextImage src={account.img} alt="No Image" fill />
                          </div>
                        ) : (
                          <PiUserLight style={{ fontSize: 32 }} />
                        )}
                        <div className={style.header_option_text}>
                          <p className={style.option_title}>Account</p>
                          <p className={style.option_sub}>{account.name}</p>
                        </div>
                      </div>
                    ) : (
                      <div
                        className={style.site_option_section}
                        onClick={() =>
                          dispatch(accountStoreActions.openSignInUI())
                        }
                      >
                        <PiUserLight style={{ fontSize: 32 }} />
                        <div className={style.header_option_text}>
                          <p className={style.option_title}>Sign In</p>
                          <p className={style.option_sub}>Account</p>
                        </div>
                        {/* <div className="secondary-btn">
                      <PiUserLight style={{ fontSize: 22 }} /> Sign In
                    </div> */}
                      </div>
                    )}
                    <div
                      className={style.site_option_section}
                      onClick={() => onOpenWishList()}
                    >
                      {wishlistLoader ? (
                        <Loader className={style.loader} />
                      ) : (
                        <div className={style.icon}>
                          <PiHeartLight />
                          <div
                            className={style.total_count}
                            data-count={favoriteCount}
                          ></div>
                        </div>
                      )}
                    </div>
                    <div
                      className={style.site_option_section}
                      onClick={() => setCartOpen(true)}
                    >
                      {cartLoader ? (
                        <Loader className={style.loader} />
                      ) : (
                        <>
                          <div className={style.icon}>
                            <PiShoppingCartLight />
                            <div
                              className={style.total_count}
                              data-count={cartCount}
                            ></div>
                          </div>
                          {totalPrice.toFixed(2) >= 0 && (
                            <div className={style.header_option_text}>
                              <p className={style.option_title}>Total</p>
                              <p className={style.option_sub}>
                                <span>{currencyType}</span>{" "}
                                {totalPrice.toFixed(2)}
                              </p>
                            </div>
                          )}
                        </>
                      )}
                    </div>
                  </>
                )}
              </div>
            </div>
          </div>
        </div>
      </div>
      <div ref={hitRef}></div>
      {cartOpen && (
        <Cart
          open={cartOpen}
          onClose={() => {
            setCartOpen((prev) => !prev);
          }}
        />
      )}
      {favoriteOpen && (
        <WishList
          open={favoriteOpen}
          onClose={() => {
            setFavoriteOpen((prev) => !prev);
          }}
        />
      )}
      <Account />
    </>
  );
};

export default Header;
