import { Badge, Dropdown, Image, Menu } from "antd";
import { FC, useContext, useEffect, useState } from "react";
import Logo from "../home/logo/Logo";
import styles from "./internalPageHeader.module.scss";
import profile from "../../mockData/profileData";
import _, { isEmpty } from "lodash";
import { useRouter } from "next/router";
import type { MenuProps } from "antd";
import Router from "next/router";
import cx from "classnames";
import * as CartApi from "../../pages/api/cart";
import {
  UserOutlined,
  DownOutlined,
  ShoppingOutlined
} from "@ant-design/icons";
import shopConetxt from "../../context/shopConetxt";
import * as CommonAPI from "../../pages/api/common";
import { baseUrl } from "../../constants/urls";
const CheckoutPageHeader: FC<any> = (props) => {
  const {
    cart,
    setCartItems,
    setIsCartLoading,
    categoryTreeNested,
    setCategoryBreadcrumb,
    setCategoryTreeNested,
    wishlist,
    setWishlistItems,
  } = useContext(shopConetxt);
  const router = useRouter();
  const [loginRes, setLoginRes] = useState<any>({});
  const [profileInfo, setProfileInfo] = useState<any>(profile || []);
  const [isOTPModalVisible, setIsOTPModalVisible] = useState(false);
  // const [cartItemCount, setCartItemCount] = useState<number>(0);
  useEffect(() => {
    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);
    //    }
    // });

  }, [router])

  // useEffect(() => {
  //   setCartItemCount(props.cartItemCount);
  // }, [cart]);

  const profileData: MenuProps["onClick"] = (e: any) => {
    if (e.key === "11") {
      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 === "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)) {
        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 },
      ]}
    />
  );

  return (
    <>
    <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>
      <div className={styles.header}>
      
        <Logo />
        <div className="flex items-center">
          {props?.page ? <div style={{ marginRight: "0.75rem" }}><Badge count={props?.cartItemCount ? props?.cartItemCount : 0} className={cx(styles.badge, "cursor-pointer")} >
            <ShoppingOutlined className={styles.itemIcons} onClick={() => { router.push("/cart"); }} />
          </Badge></div> : null}
          <Dropdown
            overlay={userMenu}
            className={cx(styles.dropdownParent)}
            trigger={["click"]}
          >
            <a onClick={(e) => e.preventDefault()}>
              <UserOutlined />
              <span >
                {!_.isEmpty(loginRes) ? `Hi ${loginRes?.data?.name}` : " Account"}
              </span>
              <DownOutlined style={{ fontSize: "10px", marginLeft: "4px" }} />
            </a>
          </Dropdown>
        </div>
      </div>
    </>
  )
}

export default CheckoutPageHeader;
