import {
  HeartOutlined,
  ShoppingOutlined,
  UserOutlined,
  DownOutlined,
  ArrowRightOutlined,
  ArrowRightOutlined as ArrowRight,
} from "@ant-design/icons";
import cx from "classnames";
import _, { get, isEmpty } from "lodash";
import { Badge, MenuProps } from "antd";
import { useRouter } from "next/router";
import Router from "next/router";
import { FC, useContext, useEffect, useState } from "react";
import SingInModal from "../../modal/singInModel/SingInModal";
import CartModal from "../../modal/cartModal/CartModal";
import MobileSideMenu from "../mobile/mobileSideMenu/MobileSideMenu";
import styles from "./navMenu.module.scss";
import * as CartApi from "../../../pages/api/cart";
import * as WishList from "../../../pages/api/wishList";
import * as CommonAPI from "../../../pages/api/common";
import OTPModal from "../../modal/otpModal/OTPModal";
import { Dropdown, Image, Menu } from "antd";
import shopConetxt from "../../../context/shopConetxt";
import profile from "../../../mockData/profileData";
import { getIdForCartUpdate } from "../../../utils/cartUtils/cartUpdateUtils";
import RequestQuoteModal from "../../productDetails/leftPane/components/RequestQuoteModal";
import { baseUrl } from "../../../constants/urls";

// New nav items as per design
const NavMenuList = [
  { displayName: "Services", groupStart: false },
  { displayName: "Enquire us", groupStart: false },
];

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 NavMenu: FC<any> = (props) => {
  const router = useRouter();
  const { cart, setCartItems, wishlist } = useContext(shopConetxt);
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [isOTPModalVisible, setIsOTPModalVisible] = useState(false);
  const [isDrawerVisible, setIsDrawerVisible] = useState(false);
  const [loginRes, setLoginRes] = useState<any>({});
  const [cartItemCount, setCartItemCount] = useState<number>(0);
  const [wishlistCount, setWishlistCount] = useState<number>(0);
  const [isCartModalVisible, setIsCartModalVisble] = useState(false);
  const [cartProduct, setCartProduct] = useState([]);
  const [productInvoice, setProductInvoice] = useState<any>({});
  const [profileInfo, setProfileInfo] = useState<any>(profile || []);
  const [isRequestQuoteModalOpen, setIsRequestQuoteModalOpen] = useState(false);

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

  useEffect(() => {
    const cityPincode = localStorage.getItem("PinCode");
    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.reload();
        }
      });
    }
    const tokenData: any = !_.isEmpty(details) ? details.token : null;
    setTimeout(() => {
      CartApi.cartFetch(tokenData).then((res) => {
        if (res.data !== null) {
          setCartItems(res.data);
          setCartItemCount(res.data.items.length);
        }
      });
      WishList.getWishList(tokenData, details?.data?.id, cityPincode, "").then(
        (res) => {
          setWishlistCount(res?.data?.length);
        }
      );
    }, 400);

    if (_.isEmpty(details)) {
      const newData: any = profileInfo.slice(0, profileInfo.length - 1);

      setProfileInfo(newData);
    }
  }, []);

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

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

  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;

    {
      /* cart Model POPUP changed as part of requirement IMN-82 */
      // CartApi.cartFetch(tokenData).then((cartRes) => {
      //   if (cartRes.data !== null) {
      //     setCartProduct(cartRes.data.items);
      //     setProductInvoice(cartRes.data);
      //     setCartItemCount(cartRes.data.items.length);
      //   }
      //   setIsCartModalVisble(!isCartModalVisible);
      // });
    }

    router.push("/cart");
  };

  const closeCart = () => {
    const tokenData: any = !_.isEmpty(loginRes) ? loginRes.token : null;
    CartApi.cartFetch(tokenData).then((res) => {
      if (res.data !== null) {
        setCartItemCount(res.data.items.length);
      } else {
        setCartItemCount(0);
      }
    });
  };

  const enuiry = (name: any) => {
    if (name === "Contact") {
      Router.push("/contactUs");
    } else if (name === "Get a Quotation") {
      setIsRequestQuoteModalOpen(true);
    } else if (name === "RFQ") {
      // if (_.isEmpty(loginRes)) {
      //   setIsOTPModalVisible(!isOTPModalVisible);
      // } else {
        Router.push("/rfq");
      // }
    } else {
      window.location.replace("#enquiryForm");
      // window.scrollTo({
      //   top: window.outerHeight*4,
      //   behavior: 'smooth',
      // });
    }
  };

  const deleteCart = (prodId: any) => {
    const prod_id = getIdForCartUpdate(
      get(prodId, "additional.product_id"),
      cart
    );
    if (prodId !== undefined) {
      const tokenData: any = !_.isEmpty(loginRes) ? loginRes.token : null;
      const params = {
        token: tokenData,
        item_id: prod_id,
      };
      CartApi.removeCartItem(params).then((res_item) => {
        setCartItems(res_item.data);
        setProductInvoice(res_item.data);
        setCartItemCount(res_item?.data?.items?.length);
      });
    }
  };

  const profileData: MenuProps["onClick"] = (e: any) => {
    if (e.key === "11") {
      localStorage.removeItem("loginDetails");
      localStorage.removeItem("PinCode");
      localStorage.removeItem("Citycode");
      localStorage.clear();
      setTimeout(() => {
        router.reload();
      }, 100);
    } 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 === "9") {
      if (_.isEmpty(loginRes)) {
        setIsOTPModalVisible(!isOTPModalVisible);
      } else {
        Router.push("/indispareRate");
      }
    } else {
      const found: any = profile.find((element: any) => element.key === e.key);

      if (_.isEmpty(loginRes)) {
        if (router.asPath == "/home") {
          setIsOTPModalVisible(!isOTPModalVisible);
        } else {
          router.push("#login");
          setIsOTPModalVisible(!isOTPModalVisible);
        }
        // setTimeout(() => {
        //   setIsOTPModalVisible(!isOTPModalVisible);
        // }, 10);
      } else {
        router.push({
          pathname: `/customerDashboard/customerDashboard`,
          query: { val: found.label },
        });
      }
    }
  };

  const patnerData: MenuProps["onClick"] = (e: any) => {
    if (e.key === "1") {
      router.push({
        pathname: `/seller/sellerLogin/login`,
      });
    } else {
      router.push({
        pathname: `/seller/sellerLogin/signup`,
      });
    }
  };

  const myPr = isEmpty(loginRes) ? "Sign In / Sign Up" : "My Profile";

  const menuExtraProps: any = !isEmpty(loginRes)
    ? {
        key: "11",
        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: "9",
          label: " Indispare Rate",
          icon: (
            <Image
              src={"/images/profileIcon/Invoice.svg"}
              height="20px"
              width="20px"
              alt="rfq"
              preview={false}
            />
          ),
          className: styles.labelData,
        },
        {
          key: "10",
          label: "User Management",
          icon: (
            <Image
              src={"/images/profileIcon/Profile.svg"}
              height="20px"
              width="20px"
              alt="mgmt"
              preview={false}
            />
          ),
          className: styles.labelData,
        },
        { ...menuExtraProps },
      ]}
    />
  );

  const patnerMenu = (
    <Menu
      onClick={patnerData}
      items={[
        {
          key: "1",
          label: "Seller Login",
          className: styles.labelDataPartner,
          icon: <ArrowRightOutlined />,
        },

        {
          key: "2",
          label: "Sell on Indispare",
          className: styles.labelDataPartner,
          icon: <ArrowRightOutlined />,
        },
      ]}
    />
  );

  return (
    <nav className="ml-auto" style={{ color: "#291C61" }}>
      <ul className="flex flex-row gap-6 items-center mb-0">
        {/* Left nav items */}
        <li className={styles.navListText} style={{ fontWeight: 400 }}>Services</li>
        <li>
          <button
            className={styles.navListText}
            style={{ fontWeight: 400, cursor: "pointer", background: "none", border: "none", padding: 0 }}
            onClick={() => window.location.replace("#enquiryForm")}
            type="button"
          >
            Enquire us
          </button>
        </li>
        {/* Seller dropdown */}
        {/* <li>
          <Dropdown overlay={patnerMenu} className={cx(styles.dropdownParent)} trigger={["click"]}>
            <a onClick={e => e.preventDefault()} className={styles.navListText} style={{ fontWeight: 400}}>
              Seller <DownOutlined style={{ fontSize: "12px", paddingLeft: "2px" }} />
            </a>
          </Dropdown>
        </li> */}
        {/* Send RFQ button */}
        <li>
          <button className={styles.rfqButton} style={{ minWidth: 110, fontWeight: 400 }} onClick={() => enuiry("RFQ")}>Send RFQ 
            {/* <ArrowRight style={{ fontSize: 18, marginLeft: 8, color: '#fff' }} /> */}
            </button>
        </li>
        {/* Shop Instantly button */}
        <li>
          <button
            style={{
              background: '#291C61',
              color: '#fff',
              border: 'none',
              padding: '6px 16px',
              borderRadius: 6,
              fontWeight: 400,
              minWidth: 130,
              cursor: 'pointer',
              display: 'flex',
              alignItems: 'center',
              gap: 8
            }}
            
            onClick={() => window.open('https://express.sparts.click/', '_blank', 'noopener,noreferrer')}
          >
            Shop Instantly 
            {/* <ArrowRight style={{ fontSize: 18, color: '#fff' }} /> */}
          </button>
        </li>
        {/* Account dropdown - new design */}
        <li>
          <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?.company_name || loginRes?.data?.name}` : " Account"}
              </span>
              <DownOutlined style={{ fontSize: "12px", paddingLeft: "2px" }} />
            </a>
          </Dropdown>
        </li>
      </ul>
      <SingInModal
        handleClose={() => {
          setIsModalVisible(false);
        }}
        isModalVisible={isModalVisible}
        page={"home"}
      />
      <OTPModal
        page={
          router.asPath === "/#login" || router.asPath === "/" ? "home" : "home"
        }
        handleOTPClose={() => {
          setIsOTPModalVisible(false);
        }}
        stateArray={props?.stateArray}
        isOTPModalVisible={isOTPModalVisible}
      />
      <MobileSideMenu
        onClose={() => {
          setIsDrawerVisible(false);
        }}
        isDrawerVisible={isDrawerVisible}
      />
      <CartModal
        handleCartClose={() => {
          setIsCartModalVisble(false);
          closeCart();
        }}
        products={cartProduct}
        productInvoice={productInvoice}
        deleteCart={deleteCart}
        isCartModalVisible={isCartModalVisible}
      />
      {isRequestQuoteModalOpen && (
        <RequestQuoteModal
          isOpen={true}
          handleModalClose={() => setIsRequestQuoteModalOpen(false)}
        />
      )}
    </nav>
  );
};

const NavMenuItem = ({
  Item,
  drawerVisible,
  setDrawerVisible,
  isOTPModalVisible,
  setIsOTPModalVisible,
  routeSeller,
  loginRes,
  cartPage,
  cart,
  enquiry,
  userMenu,
  handleWishlist,
  wishlist,
}: any) => {
  const display_name =
    loginRes?.data?.company_name == undefined ||
    loginRes?.data?.company_name == null ||
    loginRes?.data?.company_name == ""
      ? `${loginRes?.data?.name}`
      : `${loginRes?.data?.company_name}`;
  return (
    <li
      onClick={() => {
        Item.displayName === "extra"
          ? setDrawerVisible(!drawerVisible)
          : Item.displayName === "Seller with us"
          ? routeSeller()
          : Item.displayName === "cart"
          ? cartPage()
          : Item.displayName === "Enquire us" ||
            Item.displayName === "Contact" ||
            Item.displayName === "Get a Quotation" ||
            Item.displayName === "RFQ"
          ? enquiry(Item.displayName)
          : null;
        Item.displayName === "wishlist" ? handleWishlist() : null;
      }}
      key={Item.displayName}
      className={` cursor-pointer flex flex-row  justify-center items-center ${
        Item.groupStart ? "ml-5" : ""
      }`}
    >
      {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 ${display_name}` : " Account"}
            </span>
            <DownOutlined style={{ fontSize: "8px", paddingLeft: "2px" }} />
          </a>
        </Dropdown>
      ) : (
        <div className={styles.navBadgeStyle}>
          {/* <span className={cx(styles.iconContainer, "icon text-base")}>
            {Item.Icon ? (
              <Item.Icon style={{ color: "#291C61", fontSize: "25px" }} />
            ) : (
              ""
            )}
          </span> */}
          {Item.isButton ? (
            <button className={styles.rfqButton}>SEND RFQ <span className={styles.rfqArrow}>  &nbsp; ➜</span></button>
          ) : (
            <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.badgeStyle}>
                <ShoppingOutlined className={styles.itemIcons} />
              </Badge>
            </>
          ) : (
            <></>
          )}
          {Item.displayName === "wishlist" ? (
            <>
              <Badge
                count={wishlist ? wishlist : 0}
                className={styles.badgeStyle}
              >
                <HeartOutlined className={styles.itemIcons} />
              </Badge>
            </>
          ) : (
            <></>
          )}
        </div>
      )}
    </li>
  );
};

export default NavMenu;
