import { Button, Image, Input, notification } from "antd";
import {
  FacebookOutlined,
  TwitterOutlined,
  InstagramOutlined,
  YoutubeOutlined,
  LinkedinOutlined,
} from "@ant-design/icons";
import FooterOption from "./FotterOption";
import footerData from "../../../mockData/footer";
import cx from "classnames";
import styles from "./footer.module.scss";
import { FC, useContext, useEffect, useState } from "react";
import Router, { useRouter } from "next/router";
import _ from "lodash";
import OTPModal from "../../modal/otpModal/OTPModal";
import * as CommonApi from "../../../pages/api/common";
import { baseUrl } from "../../../constants/urls";
import Head from "next/head";
import MediaQuery from "react-responsive";
import { createBreadcrumb, getFlattenCategory } from "../../globalUtils/utils";
import shopConetxt from "../../../context/shopConetxt";

const Footer: FC<any> = (props) => {
   const { setCategoryTreeNested, setCategoryBreadcrumb, categoryTreeNested } =
      useContext(shopConetxt);
    const router = useRouter();
  const [loginRes, setLoginRes] = useState<any>({});
  const [isOTPModalVisible, setIsOTPModalVisible] = useState(false);
  const [email, setEmail] = useState("");
const [footerCategories, setFooterCategories] = useState<any>({
  Mechanical: {},
  Electrical: {},
  Electronics: {},
  Safety: {},
  Lubricants: {},
  OfficeEssentials: {},
});
useEffect(() => {
  const val: any = localStorage.getItem("loginDetails");
  const details = JSON.parse(val);
  setLoginRes(details);
  CommonApi.getRequest(`${baseUrl}/api/footer-category-list`).then((res) => {
  console.log("footer category list", res);
  const mechanicalCategories = res?.data?.categories?.find((item: any) =>
    item?.name?.toLowerCase()?.includes("mechanical")
  );
  const electricalCategories = res?.data?.categories?.find((item: any) =>
    item?.name?.toLowerCase()?.includes("electrical")
  );
  const electronicsCategories = res?.data?.categories?.find((item: any) =>
    item?.name?.toLowerCase()?.includes("electronics")
  );
  const safetyCategories = res?.data?.categories?.find((item: any) =>
    item?.name?.toLowerCase()?.includes("safety")
  );
  const lubricantsCategories = res?.data?.categories?.find((item: any) =>
    item?.name?.toLowerCase()?.includes("lubricants")
  );
  const officeEssentialsCategories = res?.data?.categories?.find(
    (item: any) =>
      item?.name?.toLowerCase()?.includes("office essentials")
  );
  setFooterCategories({
    Mechanical: mechanicalCategories,
    Electrical: electricalCategories,
    Electronics: electronicsCategories,
    Safety: safetyCategories,
    Lubricants: lubricantsCategories,
    OfficeEssentials: officeEssentialsCategories,
  });
 
})
    // if(props?.page=="home"){
    // const Script = document.createElement("script");
    // //id should be same as given to form element
    // const Form:any = document.getElementById('donateForm');
    // Script.setAttribute('src','https://checkout.razorpay.com/v1/payment-button.js')
    // Script.setAttribute('data-payment_button_id','pl_KwvxjT1YtpwjBp')
    // Form.appendChild(Script);
    // }
  }, []);
  const isMac =
    typeof window !== "undefined"
      ? navigator.platform.toUpperCase().indexOf("MAC") >= 0
      : false;
  const isIos = [
    "iPhone",
    "iPad",
    "iPod",
    "iPad Simulator",
    "iPhone Simulator",
    "iPod Simulator",
  ].includes(navigator.platform);

  const customerService = () => {
    if (_.isEmpty(loginRes)) {
      setIsOTPModalVisible(true);
    } else {
      Router.push("/customerSupport/customerOrder");
    }
  };
  const _submit = () => {
    const val =
      /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
    console.log(val.test(email));

    if (email === "" || (email !== "" && !val.test(email))) {
      notification.error({ message: "Please Enter Valid Email Id" });
    } else {
      const params = {
        subscriber_email: email,
      };
      CommonApi.postRequest(`${baseUrl}/api/subscribe`, params).then((res) => {
        setEmail("");
        if (res?.data?.status) {
          notification.success({ message: res?.data?.message });
        } else {
          notification.error({ message: res?.data?.message });
        }
      });
    }
  };
  const initializeRazorpay = () => {
    return new Promise((resolve) => {
      const script = document.createElement("script");
      script.src = "https://checkout.razorpay.com/v1/payment-button.js";

      script.onload = () => {
        resolve(true);
      };
      script.onerror = () => {
        resolve(false);
      };

      document.body.appendChild(script);
    });
  };

  const NavigationData = (selectedMenuItems: any) => {
    const flattenCategory = getFlattenCategory(categoryTreeNested);
      const breadCrumbData = createBreadcrumb(
        selectedMenuItems.id,
        flattenCategory
      );
      setCategoryBreadcrumb(breadCrumbData);
    router.push({
      pathname: `/products/${selectedMenuItems.id}`,
    });
  };
  return (
    <> 
      <div className={styles.footerContainer}>
        <div className={"container"}>
          <div className={styles.leadSection}>
            <h2 className={styles.leadTitle}>
              Indispare – Leading B2B e-Commerce Platform for Industrial
              Products
            </h2>
            <p className={styles.leadDescription}>
              To combat the negative impact of delays in sourcing on the
              production process, Indispare offers a hassle-free online buying
              experience, simplifying the procurement of industrial products.
              Our aim is to help you make substantial savings in supplies,
              enhance the efficiency of your inventory management, and support
              your business growth. We strive to make business-to-business
              procurement a time-saving and smooth process.
            </p>
            <p className={styles.leadDescription} style={{ marginTop: "2em" }}>
              Traditional methods of procuring industrial products and business
              supplies can be time-consuming. To simplify this process,
              Indispare has emerged as the ideal platform through which
              companies and suppliers can procure industrial tools and equipment
              efficiently.
            </p>
          </div>
          <div className={styles.popularSearches}>
            <h3>Popular searches on Indispare</h3>
            <div className={styles.popularRow}>
              {Object.entries(footerData.popularSearches).map(
                ([category, items]) => (
                  <div key={category} className={styles.categoryBox}>
                    <h4>{category.toUpperCase()}</h4>
                    <div className={styles.footerLinks}>
                     
                      {footerCategories?.[category]?.children?.map((itemf: any, i:any) => (
                        <span
                          key={i}
                          className={styles.footerLink}
                          role="button"
                          tabIndex={0}
                          onClick={() => { NavigationData(itemf); }}
                          onKeyPress={(e) => {
                            if (e.key === "Enter" || e.key === " ") {
                              NavigationData(itemf);
                            }
                          }}
                          aria-label={`Go to ${itemf?.name}`}
                        >
                          {itemf?.name}
                          {i < footerCategories?.[category]?.children?.length - 1 && " | "}
                        </span>
                      ))}
                    </div>
                  </div>
                )
              )}
            </div>
          </div>
          <div className={styles.devider}></div>

          <div className={cx("ant-row")}>
            <div
              className={cx(
                "ant-col ant-col-xs-24 ant-col-sm-24 ant-col-md-24 ant-col-xl-10 mt-5"
              )}
            >
              <div>
                <Image
                  preview={false}
                  src="/newLogoNewDesign.svg"
                  className={styles.footerImage}
                  alt="Footer Image"
                />
                <div className={cx(styles.subscribeTitle)}>
                  Subscribe to the Indispare Newsletter to receive Exclusive
                  Content, Offers and More!
                </div>
              </div>

              <form className={cx("ant-row")}>
                <Input
                  placeholder="Enter Email Address"
                  className={styles.home__footer__input}
                  value={email}
                  onChange={(e) => setEmail(e.target.value)}
                />
                <Button
                  color="pink"
                  className={styles.home__footer__button}
                  onClick={_submit}
                >
                  Subscribe
                </Button>
              </form>

              {/* {props?.page=="home"?<form id='donateForm' style={{marginTop:"1rem"}}></form>:null} */}
            </div>

            <div
              className={cx(
                "ant-col ant-col-xs-24 ant-col-sm-12 ant-col-md-8 ant-col-xl-4 mt-5"
              )}
            >
              <FooterOption title="EXPLORE" links={footerData.explore} />
            </div>
            <div
              className={cx(
                "ant-col ant-col-xs-24 ant-col-sm-12 ant-col-md-8 ant-col-xl-6 mt-5"
              )}
            >
              <FooterOption title="INFORMATION" links={footerData.customer} />
            </div>
            <div
              className={cx(
                "ant-col ant-col-xs-24 ant-col-sm-24 ant-col-md-8 ant-col-xl-4 mt-5"
              )}
            >
              <FooterOption title="LEGAL" links={footerData.legal} />
            </div>
          </div>
          <div className={cx("ant-row my-5 justify-between")}>
            <div className={cx("ant-row")}>
              {/* <div
                  className={styles.home__footer__icon_container}
                  role="button"
                  tabIndex={0}
                  onClick={() => {
                    window.open("https://www.youtube.com/@indispare");
                  }}
                  onKeyPress={(e) => {
                    if (e.key === "Enter" || e.key === " ") {
                      window.open("https://www.youtube.com/@indispare");
                    }
                  }}
                  aria-label="Open YouTube"
                >
                  <YoutubeOutlined className={styles.home__footer__icon} />
                </div> */}

              <div
                className={styles.home__footer__icon_container}
                role="button"
                tabIndex={0}
                onClick={() => {
                  window.open("https://www.facebook.com/indisparecom");
                }}
                onKeyPress={(e) => {
                  if (e.key === "Enter" || e.key === " ") {
                    window.open("https://www.facebook.com/indisparecom");
                  }
                }}
                aria-label="Open Facebook"
              >
                <Image
                  preview={false}
                  src="/images/Facebook.svg"
                  className={styles.home__footer__icon}
                  alt="facebook"
                />
                {/* <FacebookOutlined className={styles.home__footer__icon}/> */}
              </div>
              {/* <div
                  className={styles.home__footer__icon_container}
                  role="button"
                  tabIndex={0}
                  aria-label="Open LinkedIn"
                  onClick={() => {
                    window.open("https://www.linkedin.com/company/indispare/");
                  }}
                  onKeyPress={(e) => {
                    if (e.key === "Enter" || e.key === " ") {
                      window.open(
                        "https://www.linkedin.com/company/indispare/"
                      );
                    }
                  }}
                >
                  {/* <Image
                    preview={false}
                    src="/images/LinkedIn.svg"
                    className={styles.home__footer__icon}
                    alt="LinkedIn"
                  /> 
                  <LinkedinOutlined className={styles.home__footer__icon} />
                </div> */}

              <div
                className={styles.home__footer__icon_container}
                role="button"
                tabIndex={0}
                aria-label="Open Instagram"
                onClick={() => {
                  window.open("https://www.instagram.com/indispare/");
                }}
                onKeyPress={(e) => {
                  if (e.key === "Enter" || e.key === " ") {
                    window.open("https://www.instagram.com/indispare/");
                  }
                }}
              >
                <InstagramOutlined className={styles.home__footer__icon} />
              </div>
              <div
                className={styles.home__footer__icon_container}
                role="button"
                tabIndex={0}
                aria-label="Open Twitter"
                onClick={() => {
                  window.open("https://twitter.com/indispare");
                }}
                onKeyPress={(e) => {
                  if (e.key === "Enter" || e.key === " ") {
                    window.open("https://twitter.com/indispare");
                  }
                }}
              >
                {/* <Image
                    preview={false}
                    src="/images/Twitter.svg"
                    className={styles.home__footer__icon}
                    alt="twitter"
                  /> */}
                <TwitterOutlined className={styles.home__footer__icon} />
              </div>
            </div>
            <div>
              <div className={cx("ant-row", styles.footerIcon)} style={{}}>
                <div
                  className={styles.playStore}
                  role="button"
                  tabIndex={0}
                  onClick={() => {
                    window.open(
                      "https://play.google.com/store/apps/details?id=com.indispare&hl=en"
                    );
                  }}
                  onKeyPress={(e) => {
                    if (e.key === "Enter" || e.key === " ") {
                      window.open(
                        "https://play.google.com/store/apps/details?id=com.indispare&hl=en"
                      );
                    }
                  }}
                  aria-label="Open Google Play Store"
                >
                  <Image
                    preview={false}
                    src="/images/google-play.svg"
                    className={styles.home__footer__icon}
                    alt="playStore"
                  />
                  {/* <FacebookOutlined className={styles.home__footer__icon}/> */}
                </div>
                <div
                  className={styles.playStore}
                  role="button"
                  tabIndex={0}
                  onClick={() => {
                    window.open(
                      "https://apps.apple.com/us/app/indispare/id6444924860"
                    );
                  }}
                  onKeyPress={(e) => {
                    if (e.key === "Enter" || e.key === " ") {
                      window.open(
                        "https://apps.apple.com/us/app/indispare/id6444924860"
                      );
                    }
                  }}
                  aria-label="Open Apple App Store"
                >
                  <Image
                    preview={false}
                    src="/images/Apple.svg"
                    className={styles.home__footer__icon}
                    alt="appStore"
                  />
                  {/* <FacebookOutlined className={styles.home__footer__icon}/> */}
                </div>
              </div>
              {/* <MediaQuery minWidth={769}>
                        <div className={styles.playStore} onClick={()=>{window.open("https://play.google.com/store/apps/details?id=com.indispare&hl=en")}}>
                                <Image preview={false} src="/images/Google-Play_icon.jpg" className={styles.home__footer__icon} alt="playStore"/>
                            {/* <FacebookOutlined className={styles.home__footer__icon}/>
                            </div>
                        </MediaQuery> */}
              {/* <div className={styles.playStore} onClick={()=>{window.open("https://play.google.com/store/apps/details?id=com.indispare&hl=en")}}>
                                <Image preview={false} src="/images/Google-Play_icon.jpg" className={styles.home__footer__icon} alt="playStore"/>
                            {/* <FacebookOutlined className={styles.home__footer__icon}/>
                            </div> */}
            </div>
          </div>
          <div className="ant-row">
            <div className="ant-col ant-col-xl-10 ant-col-md-0 ant-col-xs-0"></div>
          </div>
          <div className={styles.home___footer___copy_right}>
            @2024 Indispare. All Rights Reserved
          </div>

          <OTPModal
            handleOTPClose={() => {
              setIsOTPModalVisible(false);
            }}
            page={"customer"}
            isOTPModalVisible={isOTPModalVisible}
            stateArray={props?.stateArray}
          />
        </div>
      </div>
    </>
  );
};
export default Footer;
