import {
  AutoComplete,
  Badge,
  Button,
  Dropdown,
  Image,
  Input,
  Menu,
  message,
  Modal,
  Select,
} from "antd";
import cx from "classnames";
import { FC, useCallback, useEffect, useState, useContext } from "react";
import { catagoriesData } from "../../mockData/catagories";
import Logo from "../home/logo/Logo";
import styles from "./internalPageHeader.module.scss";
import {
  MenuOutlined,
  AudioOutlined,
  CameraOutlined,
  HeartOutlined,
  ShoppingOutlined,
  UserOutlined,
  SearchOutlined,
  DownOutlined,
  CaretDownOutlined,
} from "@ant-design/icons";
import { debounce, isEmpty, isEqual, omit } from "lodash";
import Pincode from "../home/location/Pincode";
import MegaMenu from "../home/MegaMenu";
import type { MenuProps } from "antd";
import SingInModal from "../modal/singInModel/SingInModal";
import MobileSideMenu from "../home/mobile/mobileSideMenu/MobileSideMenu";
import { useRouter } from "next/router";
import Router from "next/router";
import * as SearchAPI from "../../pages/api/search";
import * as CartApi from "../../pages/api/cart";
import _ from "lodash";
import get from "lodash/get";
import CartModal from "../modal/cartModal/CartModal";
import OTPModal from "../modal/otpModal/OTPModal";
import shopConetxt from "../../context/shopConetxt";
import profile from "../../mockData/profileData";
import { createBreadcrumb, getFlattenCategory } from "../globalUtils/utils";
import { fetchAttributesES, fetchCatgories } from "../../pages/api/categories";
import { FiSearch } from "react-icons/fi";
import * as CategoryAPI from "../../pages/api/category";
import {
  getIncreaseQuantityPayload,
  getDecreaseQuantityPayload,
  getIdForCartUpdate,
} from "../../utils/cartUtils/cartUpdateUtils";
import Link from "next/link";

import "regenerator-runtime";
import SpeechRecognition, {
  useSpeechRecognition,
} from "react-speech-recognition";

import * as WishList from "../../pages/api/wishList";
import { useMediaQuery } from "react-responsive";
import { baseUrl } from "../../constants/urls";
import * as CommonAPI from "../../pages/api/common";
const NavSignList = [
  { displayName: "Sign In", groupStart: true, Icon: UserOutlined },
  {
    displayName: "wishlist",
    groupStart: true,
    Icon: HeartOutlined,
    hideDisplayName: true,
  },
  {
    displayName: "cart",
    groupStart: false,
    Icon: ShoppingOutlined,
    hideDisplayName: true,
  },
  // {
  //   displayName: "extra",
  //   groupStart: false,
  //   Icon: MenuOutlined,
  //   hideDisplayName: true,
  // },
];

const Suffix: any = ({ startListening, stopListening, listening, isMax }: any) => {
  return (
    <>
      <div
        className={cx(
          "flex justify-center items-center ",
          listening ? styles.cardcontainer : ""
        )}
        style={{
          width: isMax ? "40px" : "32px",
          height: isMax ? "40px" : "32px",
          border: "0.5px solid #E5E5E5",
          boxShadow: "0px 0px 2px rgba(0, 0, 0, 0.08)",
          borderRadius: "50%",
        }}
        onTouchStart={startListening}
        onMouseDown={startListening}
        onTouchEnd={stopListening}
        onMouseUp={stopListening}
      >
        <AudioOutlined
          style={{
            fontSize: isMax ? 20 : 16,
          }}
        />
      </div>
      {/* <div
        className="flex justify-center items-center"
        style={{
          width:isMax?"40px":"32px",
          height: isMax?"40px":"32px",
          border: "0.5px solid #E5E5E5",
          boxShadow: "0px 0px 2px rgba(0, 0, 0, 0.08)",
          borderRadius: "50%",
        }}
      >
        <CameraOutlined
          style={{
            fontSize: isMax?20:16,
          }}
        />
      </div> */}
    </>
  );
};

const mockVal = (str: string, repeat = 1) => ({
  value: str.repeat(repeat),
});
const InternalPageHeader: FC<any> = (props) => {
  const isMax = useMediaQuery({ minWidth: 1441 });
  const {
    cart,
    setCartItems,
    setIsCartLoading,
    categoryTreeNested,
    setCategoryBreadcrumb,
    setCategoryTreeNested,
    wishlist,
    setWishlistItems,
  } = useContext(shopConetxt);

  const router = useRouter();
  const searchParams = router?.query?.search;
  const categoryCode = router?.query?.id;
  const [selectedCategory, setSelectedCategory] = useState<any>("All");
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [isDrawerVisible, setIsDrawerVisible] = useState(false);
  const [isVisible, setVisibility] = useState(false);
  const [selectedCat, setSelectedCat] = useState({});
  const [searchTerm, setSearchTerm] = useState(searchParams);
  const [category, setCategory] = useState([]);
  const [subCat, setSubCat] = useState({});
  const [sellerBrands, setSellerBrands] = useState([]);
  const [categoryTree, setCategoryTree] = useState([]);
  const [autoComplete, setAutoComplete] = useState([]);
  const [cartItemCount, setCartItemCount] = useState<number>(0);
  const [wishlistCount, setWishlistCount] = useState<number>(0);
  const [isCartModalVisible, setIsCartModalVisble] = useState(false);
  const [loginRes, setLoginRes] = useState<any>({});
  const [productInvoice, setProductInvoice] = useState<any>({});
  const [isOTPModalVisible, setIsOTPModalVisible] = useState(false);
  const [profileInfo, setProfileInfo] = useState<any>(profile || []);
  const [brandList, setBrandList] = useState<any>({});
  const hideModal = () => setVisibility(false);
  const showModal = (selectedCat: any) => () => {
    categoryTree.forEach((element: any) => {
      if (element.name == selectedCat.name) {
        setSubCat(element);
      }
    });
    setSelectedCat(selectedCat);
    if (selectedCat.name === "Mechanical") {
      setTimeout(() => {
        setVisibility(true);
      }, 1000);
    }
  };

  useEffect(() => {
    CategoryAPI.fetchHomeCategory().then((res) => {
      setCategory(res);
     
    });
    setTimeout(() => {
      fetchCatgories({ category_id: 1 }).then((res) =>
        setCategoryTreeNested(get(res, "categories[0]", {}))
      );
      // CategoryAPI.fetchCategory().then((res) => {
      //   if (res) res.sort((a: any, b: any) => a.name.localeCompare(b.name));
      //   setCategory(res);
      // });
      
      const _activeFilterES = {
        q: {
          from: 1,
          size: 1000,
          "query": { "query_string": { "query": '*' } }
        },
        index: "attributes_index",
      };
      fetchAttributesES(_activeFilterES).then((res: any) => {
        const _attr = res.hits.hits;
        const _attr_ = _attr.filter((attr: any) => {
          return attr._source.code == 'brand';
        });
        if (_attr_.length > 0) {
          const _attribute_opts = (_attr_[0]._source.attribute_opts).split(",");
          //const _attribute_values = (_attr_[0]._source.attribute_values).split(",");
          setSellerBrands(_attribute_opts)
        }
      });
    }, 10); 
  }, []);
  useEffect(() => {
    setTimeout(() => {
      fetchCatgories({ category_id: 1 }).then((res) =>
      setCategoryTreeNested(get(res, "categories[0]", {}))

    );
      const code = router?.query?.id;
    const cityPincode = localStorage.getItem("PinCode");
    if (code !== "1") {
      setSelectedCategory(get(router, "query.id", "1"));
    }
    const val: any = localStorage.getItem("loginDetails");
    const details = JSON.parse(val);
    setLoginRes(details);
    if(!isEmpty(details)){
      CommonAPI.getRequest(`${baseUrl}/api/check-user/email?source=${details?.data?.email}`).then((res)=>{
       
        if(res?.data?.status==false){
          localStorage.removeItem("loginDetails");
          localStorage.removeItem("PinCode");
          localStorage.removeItem("Citycode");
          localStorage.clear()
          router.push({
            pathname: `/home`,
          });
        
        }
      })
    }
    if (_.isEmpty(details)) {
      const newData: any = profileInfo.slice(0, profileInfo.length - 1);

      setProfileInfo(newData);
    }
    const tokenData: any = !_.isEmpty(details) ? details.token : null;
    CartApi.cartFetch(tokenData).then((res) => {
      if (cart.length === 0) {
        setCartItemCount(res?.data?.items?.length);
        setCartItems(res?.data);
      }
    });

    WishList.getWishList(tokenData, details?.data?.id, cityPincode,"").then((res) => {
      setWishlistCount(res?.data?.length);
      setWishlistItems(res);
    });

   
    }, 20);
    
  }, []);

  useEffect(() => {
    setCartItemCount(cart.length);
  }, [cart]);

  useEffect(() => {
    setWishlistCount(wishlist.length);
  }, [wishlist]);

  useEffect(() => {
    // setCategory(props.catagories);
    setCategoryTree(props.categoryTree);

    const val = props.catagories.find(
      (element: any) => element.id === router?.query?.id
    );

    if (val === undefined) {
      setSelectedCategory("All");
    }
  }, [props.catagories, props.categoryTree]);

  const becomeSeller = (): any => {
    router.push({
      pathname: `/seller/sellerLogin/signup`,
    });
  };

  const searchHandler = async () => {
    const idx = get(router, "query.id", "1");
    if (searchTerm != "") {
    if (
      !isEqual(selectedCategory, "All") ||
      (idx !== selectedCategory && selectedCategory !== "All")
    ) {
      let val;

      if (
        categoryTreeNested !== undefined &&
        categoryTreeNested.hasOwnProperty("0")
      ) {
        val = Object.values(categoryTreeNested)[0];
      } else {
        val = categoryTreeNested;
      }

      const flattenCategory = getFlattenCategory(val);

      const breadCrumbData = createBreadcrumb(
        selectedCategory,
        flattenCategory
      );

      setCategoryBreadcrumb(breadCrumbData);
    } else {
      setCategoryBreadcrumb([{}]);
    }
    router.push({
      pathname: `/products/${selectedCategory}`,

      query: {
        search: searchTerm,
        id: selectedCategory,
      },
    });
  }
  };

  const profileData: MenuProps["onClick"] = (e: any) => {
    if (e.key === "12") {
      localStorage.removeItem("loginDetails");
      localStorage.removeItem("PinCode");
      localStorage.removeItem("Citycode");
      localStorage.clear()
      router.push({
        pathname: `/home`,
      });
    } else if (e.key === "7") {
      if (_.isEmpty(loginRes)) {

        setIsOTPModalVisible(!isOTPModalVisible);
      } else {
        Router.push("/customerSupport/customerOrder");
      }
    } else if (e.key === "8") {
      if (_.isEmpty(loginRes)) {

        setIsOTPModalVisible(!isOTPModalVisible);
      } else {
        Router.push("/rfq");
      }
    }else if (e.key === "10") {
      if (_.isEmpty(loginRes)) {

        setIsOTPModalVisible(!isOTPModalVisible);
      } else {
        Router.push("/indispareRate");
      }
    } else {
      const found: any = profile.find((element: any) => element.key === e.key);
      if (_.isEmpty(loginRes)) {
        setIsOTPModalVisible(!isOTPModalVisible);
      } else {
        router.push({
          pathname: `/customerDashboard/customerDashboard`,
          query: { val: found.label },
        });
      }
    }
  };
  const myPr = isEmpty(loginRes) ? "Sign In / Sign Up" : "My Profile";
  const menuExtraProps: any = !isEmpty(loginRes)
    ? {
      key: "12",
      label: "Logout",
      icon: (
        <Image
          src={"/images/profileIcon/Logout.svg"}
          height="20px"
          width="20px"
          alt="My Profile"
          preview={false}
        />
      ),
      className: styles.labelData,
    }
    : null;
  const userMenu = (
    <Menu
      onClick={profileData}
      items={[
        {
          key: "1",
          label: myPr,
          icon: (
            <Image
              src={"/images/profileIcon/Profile.svg"}
              height="20px"
              width="20px"
              alt="My Profile"
              preview={false}
            />
          ),
          className: styles.labelData,
        },
        {
          key: "2",
          label: "My Orders",
          icon: (
            <Image
              src={"/images/profileIcon/Orders.svg"}
              height="20px"
              width="20px"
              alt="My Profile"
              preview={false}
            />
          ),
          className: styles.labelData,
        },
        // {
        //   key: "3",
        //   label: "My Quotations",
        //   icon: (
        //     <Image
        //       src={"/images/profileIcon/Quotation.svg"}
        //       height="20px"
        //       width="20px"
        //       alt="My Profile"
        //       preview={false}
        //     />
        //   ),
        //   className: styles.labelData,
        // },
        {
          key: "4",
          label: "Address Book",
          icon: (
            <Image
              src={"/images/profileIcon/Address.svg"}
              height="20px"
              width="20px"
              alt="My Profile"
              preview={false}
            />
          ),
          className: styles.labelData,
        },
        {
          key: "5",
          label: "Sales Order",
          icon: (
            <Image
              src={"/images/profileIcon/Invoice.svg"}
              height="20px"
              width="20px"
              alt="My Profile"
              preview={false}
            />
          ),
          className: styles.labelData,
        },
        {
          key: "6",
          label: "My Wishlist",
          icon: (
            <Image
              src={"/images/profileIcon/MyWishlist.svg"}
              height="20px"
              width="20px"
              alt="My Profile"
              preview={false}
            />
          ),
          className: styles.labelData,
        },
        {
          key: "7",
          label: "Customer Service",
          icon: (
            <Image
              src={"/images/profileIcon/CustomerService.svg"}
              height="20px"
              width="20px"
              alt="My Profile"
              preview={false}
            />
          ),
          className: styles.labelData,
        },
{
          key: "8",
          label: "RFQ",
          icon: (
            <Image
              src={"/images/profileIcon/Invoice.svg"}
              height="20px"
              width="20px"
              alt="rfq"
              preview={false} 
            />
          ),
          className: styles.labelData,

        },
        {
          key: "10",
          label: " Indispare Rate",
          icon: (
            <Image
              src={"/images/profileIcon/Invoice.svg"}
              height="20px"
              width="20px"
              alt="rfq"
              preview={false} 
            />
          ),
          className: styles.labelData,

        },
        {
          key: "11",
          label: "User Management",
          icon: (
            <Image
              src={"/images/profileIcon/Profile.svg"}
              height="20px"
              width="20px"
              alt="mgmt"
              preview={false} 
            />
          ),
          className: styles.labelData,

        },
       
        { ...menuExtraProps },
      ]}
    />
  );
  const renderTitle = (title: string) => (
    <span style={{fontSize:"14px"}}>
      {title}
    </span>
  );
  const renderItem = (title: string, text: string) => ({
    value: title,
    label: (
      <div style={{fontSize:"16px"}}>
        {title}
      </div>
    ),
  });

  const renderCatItem = (title: string, id: any) => ({
    value: id,
    label: (
      <div style={{fontSize:"16px"}}>
        {title}
      </div>
    ),
  });
  function containsNumbers(str: any) {
    return /[0-9]/.test(str);
  }
  const _searchText = (text: any = searchTerm) => {
		// setAutoComplete([]);
		const searchOptions:any = [
			{
			  label: renderTitle('Suggestions'),
			  options: [],
			},
			{
			  label: renderTitle('Categories'),
			  options: [],
			},
			{
			  label: renderTitle('Brands'),
			  options: [],
			},
		  ];
		SearchAPI.fetchAutoCompleteWithMultiCall(text).then((resMulti:any) => {
			const res = resMulti[0];
			const array_strng: any = [];
			const array_strng_GroupBy: any = [];
			const array_strng_Brands: any = [];
			searchOptions[0].options = [];
			if(res?.hits?.hits.length > 0){
				res?.hits?.hits?.forEach((element: any) => {

					const name =
						element._source.name === null
							? element._source.product_number
							: element._source.name;
	
					if(element._source.groupby_key != ''){
						if(array_strng_GroupBy.indexOf(element._source.groupby_key) == -1){
							array_strng_GroupBy.push(element._source.groupby_key);
							array_strng.push(renderItem(element._source.groupby_key,text));
						}
					}else{
						array_strng.push(renderItem(name,text));
					}
					if(element._source.brand_label != ''){
						if(array_strng_Brands.indexOf(element._source.brand_label) == -1)
						array_strng_Brands.push(element._source.brand_label);
					}
	
				});
				searchOptions[0].options = [...array_strng];
			}			
			const array_cat: any = [];
			const res_cat = resMulti[1];
			searchOptions[1].options = [];
			if(res_cat?.hits?.hits.length > 0){
				res_cat?.hits?.hits?.forEach((element: any) => {
					const _sourceCat = element._source;
					array_cat.push(renderCatItem(_sourceCat.name,'Cat_'+_sourceCat.id));
				});
				searchOptions[1].options = [...array_cat];
			} 
			searchOptions[2].options = [];
			sellerBrands.map((itm:any)=>{
				if((itm?.toLowerCase())?.includes((text?.trim())?.toLowerCase()) && array_strng_Brands?.indexOf(itm) == -1)
				searchOptions[2].options.push(renderItem(itm,text));
			});
			array_strng_Brands.map((itm:any)=>{
        if((itm?.toLowerCase())?.includes((text?.trim())?.toLowerCase()) && array_strng_Brands?.indexOf(itm) == -1)
				searchOptions[2]?.options.push(renderItem(itm,text));
			});
			if(!(searchOptions[0]?.options?.length == 0 && searchOptions[1]?.options?.length == 0 && searchOptions[2]?.options?.length == 0 )){
				setAutoComplete(searchOptions);
			}else{
				setAutoComplete([]);
			}
			resetTranscript();
		});
	};

  // useEffect(() => {
  //   setAutoComplete([]);
  //   if (searchTerm != "") {
  //     _searchText(searchTerm);
  //   }
  // }, [searchTerm]);

  const {
    transcript,
    listening,
    resetTranscript,
    browserSupportsSpeechRecognition,
  } = useSpeechRecognition();

  // if (!browserSupportsSpeechRecognition) {
  //   return <span>Browser doesn't support speech recognition.</span>;
  // }
  const startListening = () =>
    SpeechRecognition.startListening({ continuous: true });
  const stopListening = () => {
    SpeechRecognition.stopListening();
    if (transcript != "") {
      setSearchTerm(transcript);
    }
  };

  const handleWishlist = () => {
    if (_.isEmpty(loginRes)) {
      setIsOTPModalVisible(!isOTPModalVisible);
    } else {
      router.push(
        {
          pathname: `/customerDashboard/customerDashboard`,
          query: { val: "My Wishlist" },
        }
       
      );
    }
  };

  const cartPage = () => {
    const tokenData: any = !_.isEmpty(loginRes) ? loginRes.token : null;

    // CartApi.cartFetch(tokenData).then((cartRes) => {
    //   if (cartRes.data !== null) {
    //     setProductInvoice(cartRes.data);
    //     setCartItemCount(cartRes.data.items.length);
    //   }
    //   if (!props?.page) {
    //     setIsCartModalVisble(!isCartModalVisible);
    //   }
    // });

    router.push("/cart");

  };

  const deleteCartdata = (prodId: any) => {
    const prod_id = getIdForCartUpdate(
      get(prodId, "additional.product_id"),
      cart
    );

    if (prodId !== undefined) {
      setIsCartLoading(true);
      const tokenData: any = !_.isEmpty(loginRes) ? loginRes.token : null;
      const params = {
        token: tokenData,
        item_id: prod_id,
      };
      CartApi.removeCartItem(params).then((res_item) => {
        setIsCartLoading(false);
        setCartItems(res_item.data);
        setProductInvoice(res_item.data);
        setCartItemCount(res_item?.data?.items?.length);
      });
    }
  };
  const handleAutoCompleteChange = useCallback(debounce(_searchText, 1000), []);

  const redirectIfCat = (option: any, evt: any) => {
    const val = option.value;
    if (val.includes('Cat_')) {
    
      const num1 = parseInt(val.replace('Cat_', ''))
      const flattenCategory = getFlattenCategory(categoryTreeNested);

      const breadCrumbData = createBreadcrumb(
        num1,
        flattenCategory
      );

     

      setCategoryBreadcrumb(breadCrumbData);
      router.push({
        pathname: `/products/${val.replace('Cat_', '')}`,
        query: {
          search: '',
          id: val.replace('Cat_', ''),
        },
      });
    } else {
      if (evt != '')
        setSearchTerm(evt);
    }
  }
  return (
    <>
      <div className={styles.internalPageContainer}>
        <div className={styles.firstChildHeader}>
          <ul className={styles.topNavLeft}>
          <div className={cx(styles.contactUsEmailTotal)}>For any query, email us at <span className={styles.contactUsEmail}><a href="mailto:contact@indispare.com">contact@indispare.com</a></span> or call us on  <span className={styles.contactUsEmail}>+91 8977028189</span></div>
          </ul>

          <ul className={styles.topNavRight}>
            <li onClick={()=>{router.push("/rfq");}}>
              <a>RFQ</a>
            </li>
            {/* <li>
              <a>Shipping</a>
            </li> */}
            <li onClick={() => { router.push("/faq") }}>
              <a>FAQ</a>
            </li>
            <li
              onClick={() => {
                Router.push("/contactUs");
              }}
            >
              <a>Contact</a>
            </li>
            <li onClick={becomeSeller}>
              <a>Sell on Indispare </a>
            </li>
            {/* <li>
              <a>Compare Products </a> as per client requirement
            </li> */}
          </ul>
        </div>
        
        <div className={styles.secondChildHeader}>
          <div className={styles.spareLGInnerHeader}>
            <Link href={"/"} passHref>
              <a >
                <Logo />
              </a>
            </Link>

            <div
              className={styles.categoryIcon}
              onClick={showModal({ name: "Mechanical" })}
            >
              <div className={styles.categoryText}>Browse Category</div>
              <MenuOutlined />
            </div>
            <div className={styles.pincodeContainer}>
              <Pincode />
            </div>
          </div>
          <div className={cx("ant-col ant-col-xl-10", styles.searchCol)}>
            <div className={styles.inputGroupMain}>
              <Select
                defaultValue="All Category"
                className={styles.searchDropdown}
                onChange={(value) => setSelectedCategory(value)}
                suffixIcon={<CaretDownOutlined className="ant-select-suffix" />}
              >
                <Select.Option value={"All Category"} key={"All Category"}>
                  All Category
                </Select.Option>
                {category.map((cat: any) => (
                  <Select.Option value={cat.id} key={cat.id}>
                    {cat.name}
                  </Select.Option>
                ))}
              </Select>
              <AutoComplete
                autoFocus={false}
                backfill={false}
                value={searchTerm}

                options={autoComplete}
                className={styles.inputBox}
                onChange={(evt: any) => browserSupportsSpeechRecognition?handleAutoCompleteChange(evt):_searchText(evt)}
                onSearch={(evt: any) => {
                  setSearchTerm(evt);
                }}
                onSelect={(evt: any, value: any) => {
                  redirectIfCat(value, evt)
                }}
                onKeyDown={(event: any) => {
                  if (event.keyCode === 13) {
                    searchHandler();
                  }
                }}
              >
                <Input
                  placeholder="Search Products by title, sku, category, brand etc."
                  suffix={browserSupportsSpeechRecognition ?
                    <Suffix
                      isMax={isMax}
                      startListening={startListening}
                      stopListening={stopListening}
                      listening={listening}
                    /> : null
                  }
                />
              </AutoComplete>
              <Button
                type="primary"
                className={styles.buttonMain}
                onClick={searchHandler}
              >
                <span className={styles.textSearch}>Search</span>
                <FiSearch style={{ fontSize: "16px", marginLeft: "1em" }} />
              </Button>
            </div>
          </div>
          <ul className="flex flex-row gap-1 mb-0 mr-1">
            {NavSignList.map((Item) => (
              <NavMenuItem
                key={Item.displayName}
                Item={Item}
                isOTPModalVisible={isOTPModalVisible}
                setIsOTPModalVisible={setIsOTPModalVisible}
                isDrawerVisible={isDrawerVisible}
                setDrawerVisible={setIsDrawerVisible}
                cart={cartItemCount}
                wishlist={wishlistCount}
                handleWishlist={handleWishlist}
                cartPage={cartPage}
                loginRes={loginRes}
                userMenu={userMenu}
              />
            ))}
          </ul>
        </div>
        <div className={cx("ant-col ant-col-xl-10", styles.searchShowHideCol)}>
          <div className={styles.inputGroupMain}>
            <Select
              style={{ width: "120px !important" }}
              defaultValue="All Category"
              className={styles.searchDropdown}
              onChange={(value) => setSelectedCategory(value)}
            >
              <Select.Option value={"All Category"} key={"All Category"}>
                All Category
              </Select.Option>
              {category.map((cat: any) => (
                <Select.Option value={cat.id} key={cat.id}>
                  {cat.name}
                </Select.Option>
              ))}
            </Select>
            <AutoComplete
              value={searchTerm}
              placeholder="Search Products by title, supplier, sku, category, brand etc."
              options={autoComplete}
              className={styles.inputBoxShowHide}
              onChange={(evt: any) => {
                setSearchTerm(evt);
                //_searchText(evt);
              }}
              onSelect={(evt: any, value: any) => {
                redirectIfCat(value, evt)
              }}
              onSearch={(evt: any) => {
                setSearchTerm(evt);
                //_searchText(evt);
              }}
              onKeyDown={(event: any) => {
                if (event.keyCode === 13) {
                  searchHandler();
                }
              }}
            ></AutoComplete>
            <Button
              type="primary"
              className={styles.buttonMain}
              onClick={searchHandler}
            >
              <span className={styles.textSearch}>Search</span>
              <SearchOutlined />
            </Button>
          </div>
        </div>
        <Modal
          visible={isVisible}
          onCancel={hideModal}
          footer={null}
          style={{ top: "8%" }}
          bodyStyle={{
            height: "85vh",
            backgroundColor: "#F5F5F5",
            padding: "0em",
            borderRadius: "10px",
          }}
          width={"100%"}
          className={styles.modalStyles}
        >
          <MegaMenu selectedCat={selectedCat} dataTree={subCat}
          categoryTree={categoryTree}
          brandList={brandList}
          category={category}/>
        </Modal>
        <SingInModal
          handleClose={() => {
            setIsModalVisible(false);
          }}
          isModalVisible={isModalVisible}
          page={"internal"}
        />
        <MobileSideMenu
          onClose={() => {
            setIsDrawerVisible(false);
          }}
          isDrawerVisible={isDrawerVisible}
        />
        {isCartModalVisible ? (
          <CartModal
            handleCartClose={() => setIsCartModalVisble(false)}
            products={cart}
            productInvoice={productInvoice}
            deleteCart={deleteCartdata}
            isCartModalVisible={isCartModalVisible}
          />
        ) : null}
        <OTPModal
          handleOTPClose={() => {
            setIsOTPModalVisible(false);
          }}
          isOTPModalVisible={isOTPModalVisible}
          stateArray={props?.stateArray}
        />
      </div>
    </>
  );
};

const NavMenuItem = ({
  Item,
  drawerVisible,
  setDrawerVisible,
  isOTPModalVisible,
  setIsOTPModalVisible,
  routeSeller,
  cartPage,
  loginRes,
  cart,
  handleWishlist,
  wishlist,
  userMenu,
}: any) => {
  return (
    <li
      onClick={() => {
        Item.displayName === "extra"
          ? setDrawerVisible(!drawerVisible)
          : // : Item.displayName === "Sign In"
          // 	? setIsOTPModalVisible(!isOTPModalVisible)
          Item.displayName === "Seller with us"
            ? routeSeller()
            : Item.displayName === "cart"
              ? cartPage()
              : null;
        Item.displayName === "wishlist" ? handleWishlist() : null;
      }}
      key={Item.displayName}
      className={`  cursor-pointer flex flex-row gap-1 justify-center items-center ${Item.groupStart ? "ml-0" : ""
        }`}
    >
      {Item.displayName === "Sign In" ? (
        <Dropdown
          overlay={userMenu}
          className={cx(styles.dropdownParent)}
          trigger={["click"]}
        >
          <a onClick={(e) => e.preventDefault()}>
            <UserOutlined />
            <span className={cx(styles.dropdownParentSpan)}>
              {!_.isEmpty(loginRes) ? `Hi ${loginRes?.data?.name}` : " Account"}
            </span>
            {/* <DownOutlined style={{ fontSize: "10px", marginLeft: "-4px" }} /> */}
            <CaretDownOutlined className="ant-select-suffix" />
          </a>
        </Dropdown>
      ) : (
        <div className={styles.badgeStyle}>
          <span className={cx(styles.iconContainer, "icon text-base")}>
            {Item.Icon && Item.displayName === "extra" ? (
              <Item.Icon style={{ color: "#291C61", fontSize: "25px" }} />
            ) : (
              <></>
            )}
          </span>
          <span className={styles.navListText}>
            {Item.hideDisplayName ? "" : Item.displayName}
          </span>

          {/* {Item.displayName === "cart" && cart !== 0 ? (
            <span className={styles.cartText}>
              {Item.displayName === "cart" ? `${cart}` : null}
            </span>
          ) : null}
          {Item.displayName === "wishlist" &&
          wishlist !== 0 &&
          !_.isEmpty(loginRes) ? (
            <span className={styles.cartText}>
              {Item.displayName === "wishlist" ? `${wishlist}` : null}
            </span>
          ) : null} */}

          {Item.displayName === "cart" ? (
            <>
              <Badge count={cart ? cart : 0} className={styles.badge}>
                <ShoppingOutlined className={styles.itemIcons} />
              </Badge>
            </>
          ) : (
            <></>
          )}
          {Item.displayName === "wishlist" ? (
            <>
              <Badge count={wishlist ? wishlist : 0} className={styles.badge}>
                <HeartOutlined className={styles.itemIcons} />
              </Badge>
            </>
          ) : (
            <></>
          )}
        </div>
      )}
    </li>
  );
};
export default InternalPageHeader;
