"use client";

import {
  Navbar,
  Container,
  Nav,
  Offcanvas,
  Badge,
  OverlayTrigger,
  Tooltip,
  InputGroup,
  Dropdown,
} from "react-bootstrap";
import {
  faBagShopping,
  faBars,
  faBell,
  faBoxOpen,
  faCartShopping,
  faHeart,
  faMagnifyingGlass,
  faPhone,
  faRightFromBracket,
  faShieldHalved,
  faSortDown,
  faUser,
  faWallet,
} from "@fortawesome/free-solid-svg-icons";
import "./Header.css";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { Form } from "react-bootstrap";
import { useEffect, useRef, useState } from "react";
import Login_Modal from "../common-components/common_modal/login_modal/Login_Modal";
import Reset_Password_Modal from "../common-components/common_modal/reset_password_modal/Reset_Password_Modal";
import Set_New_Password_Modal from "../common-components/common_modal/set_new_password_modal/Set_New_Password_Modal";
import Success_Modal from "../common-components/common_modal/success_modal/Success_Modal";
import Use_Current_Location from "../common-components/common_modal/Use_Current_Location/Use_Current_Location";
// import Current_Location_Offcanvas from "./current_location_offcanvas/Current_Location_Offcanvas";
import { useDispatch, useSelector } from "react-redux";
import { getAllCart, postToLoginCart } from "../../features/cart/cartSlice";
import {
  allCurrency,
  appSetup,
  setCurrentCurrency,
  SocialLink,
} from "../../features/master/masterSlice";
import { getAllWishlist } from "../../features/wishlist/wishlistSlice";

import Cookies from "js-cookie";
import { usePathname, useRouter } from "next/navigation";
import Link from "next/link";
import { getAllProducts } from "../../features/products/productsSlice";

function Header() {
  const renderTooltip = (label) => (props) => (
    <Tooltip id="button-tooltip" {...props}>
      {label}
    </Tooltip>
  );
  const [showSearch, setShowSearch] = useState(false);
  const [showResetModal, setShowResetModal] = useState(false);
  const [showSetPassModal, setShowSetPassModal] = useState(false);
  const [showSuccessModal, setShowSucsessModal] = useState(false);
  const [showAccountCreted, setShowAccountCreted] = useState(false);
  const [showLogin, setShowLogin] = useState(false);

  const searchRef = useRef(null);
  const [showOffcanvas, setShowOffcanvas] = useState(false);
  const [showLoginModal, setShowLoginModal] = useState(false);
  const [modalShow, setModalShow] = useState(false);
  const [offCanvasShow, setOffCanvasShow] = useState(false);
  const [showLogoutModal, setshowLogoutModal] = useState(false);
  const handleClose = () => setShowOffcanvas(false);
  const handleShow = () => setShowOffcanvas(true);
  const [showConfimLocModal, setShowConfimLocModal] = useState(false);
  const [searchTerm, setSearchTerm] = useState("");
  const [expanded, setExpanded] = useState(false);
  //  const [modalShow, setModalShow] = useState(false);
  const dispatch = useDispatch();

  const currentPath = usePathname();
  const isActive = (path) => currentPath === path;

  const isSignin = useSelector((state) => state.auth.is_signin);
  const currentCurrency = useSelector((state) => state.master.currentCurrency);
  const currency = useSelector((state) => state.master.all_currency);
  useEffect(() => {
    dispatch(allCurrency());
  }, [dispatch]);

  useEffect(() => {
    if (currency.length && !currentCurrency) {
      dispatch(setCurrentCurrency(currency[0]));
    }
  }, [currency, currentCurrency, dispatch]);

  const allcartData = useSelector((state) => state.cart.allCarts);
  useEffect(() => {
    dispatch(getAllCart(isSignin));
    dispatch(appSetup());
  }, [dispatch]);

  const allWishlist = useSelector((state) => state.wishlist.allWishlist);

  useEffect(() => {
    const loginCart = async () => {
      if (isSignin) {
        const res = await dispatch(postToLoginCart());
        if (res.meta?.requestStatus === "fulfilled") {
        } else if (res.meta?.requestStatus === "rejected") {
          console.log("Error:", res.payload || "Login Cart Post Failed");
        }
      }
      await dispatch(getAllCart(isSignin));
    };

    loginCart();
  }, [dispatch, isSignin]);
  const [email, setEmail] = useState();
  const [contact, setContact] = useState();
  const navigate = useRouter();

  const handleKeyPress = (e) => {
    if (e.key === "Enter" && searchTerm.trim() !== "") {
      navigate.push(`/
        `);
      // navigate.push(`/shop`);
    }
  };

  // const handleSearchClick = async () => {
  //   if (searchTerm.trim() !== "") {
  //     navigate.push(`/shop?search=${encodeURIComponent(searchTerm)}`);
  //     // navigate.push(`/shop`);

  //   }
  // };

  useEffect(() => {
    const handleOutsideClick = (event) => {
      if (searchRef.current && !searchRef.current.contains(event.target)) {
        setShowSearch(false);
      }
    };
    document.addEventListener("mousedown", handleOutsideClick);
    return () => document.removeEventListener("mousedown", handleOutsideClick);
  }, []);

  const app_setup = useSelector((state) => state?.master?.app_setup);
  const sociallink = useSelector((state) => state?.master?.social_link);
  const getallproduct = useSelector((state) => state?.product?.allProducts);

  // Wishlist & notifications
  useEffect(() => {
    dispatch(getAllWishlist());
    dispatch(getAllProducts());
  }, [dispatch]);

  useEffect(() => {
    dispatch(SocialLink());
  }, [dispatch]);

  // const handleSearchClick = async () => {
  //   if (!searchTerm?.trim()) return;
  //   await dispatch(
  //     getAllProducts({
  //       name: searchTerm,
  //     })
  //   );
  //   navigate.push(`/shop`);
  // };

  // const handleSearchClick = async () => {
  //   if (!searchTerm?.trim()) return;
  //   await dispatch(
  //     getAllProducts({
  //       name: searchTerm,
  //     })
  //   );
  //   navigate.push(
  //     `/shop?search=${encodeURIComponent(searchTerm)}`
  //   );
  // };

  const handleSearchClick = () => {
    if (!searchTerm?.trim()) return;
    // dispatch(
    //   getAllProducts({
    //     name: searchTerm,
    //   })
    // );
    navigate.push(`/?search=${encodeURIComponent(searchTerm)}`);
  };

  const notifications = [];

  const current_location = useSelector(
    (state) => state.location.current_location,
  );

  const isSignIn = useSelector((state) => state.auth.is_signin);

  const goToNotificationsTab = () => {
    navigate.push("/account", { state: { selectedTab: "third" } });
  };

  const navLinks = [
    { path: "/", label: "Home" },
    { path: "/all-products/", label: "Products" },
    // { path: "/shop/", label: "Shop" },
    { path: "/blog/", label: "Blog" },
    { path: "/contact-us/", label: "Contact Us" },
    // { path: "/career", label: "Career" },
  ];

  useEffect(() => {
    const current_location = Cookies.get("current_location_gurukrupa");
    if (!current_location) {
      setOffCanvasShow(true);
    }
  }, []);

  return (
    <>
      <section className="Header">
        <div className="top_headers_holder">
          <div className="top_header">
            <div className="container">
              <div className="top_header_bar thnk_col_2">
                <div className="top_header_col1">
                  <p className="content_html">WELCOME TO SHRI GIRRAJ</p>
                </div>
                <div className="top_header_col2">
                  <div className="content_social">
                    <ul className="social_icon">
                      {sociallink?.map((item, index) => (
                        <li
                          key={index}
                          onClick={() => window.open(item?.url, "_blank")}
                        >
                          <img
                            src={process.env.NEXT_PUBLIC_IMG_URL + item?.image}
                            className="icons"
                            alt="social"
                          />
                        </li>
                      ))}
                    </ul>
                  </div>
                </div>
              </div>
            </div>
          </div>

          <div className="middle_header">
            <div className="container">
              <div className="all_divs_holder">
                {/* Logo */}
                <div className="logo_div" onClick={() => navigate.push("/")}>
                  <img
                    src={process.env.NEXT_PUBLIC_IMG_URL + app_setup?.logo}
                    // src={"/assets/images/logo/Logo.png"}
                    className="logo_img"
                    alt="logo"
                  />
                </div>

                <div className="search_input_div">
                  <InputGroup>
                    <Form.Control
                      placeholder="Search Product"
                      value={searchTerm}
                      onChange={(e) => setSearchTerm(e.target.value)}
                      onKeyDown={handleKeyPress}
                    />
                    <InputGroup.Text
                      onClick={handleSearchClick}
                      style={{ cursor: "pointer" }}
                    >
                      <FontAwesomeIcon
                        icon={faMagnifyingGlass}
                        className="search_icon"
                      />
                    </InputGroup.Text>
                  </InputGroup>
                </div>

                <div className="three_box_div ">
                  <div
                    className="box_div address_box"
                    onClick={() => {
                      setOffCanvasShow(true);
                      // setModalShow(true);
                    }}
                  >
                    {/* <p className="title_text">
                      My Location{" "}
                      <FontAwesomeIcon
                        icon={faSortDown}
                        className="inner_icon"
                      />
                    </p> */}
                    <p className="sub_text">
                      <span className="title_span address_text">
                        {current_location?.formatted_address}
                      </span>
                    </p>
                  </div>

                  {!isSignIn && (
                    <div className="box_div border_box login_box">
                      <p className="title_text login-signup-text">
                        Login / Signup
                      </p>
                      <p
                        className="sub_text"
                        onClick={() => {
                          setShowLoginModal(true);
                        }}
                      >
                        <span className="title_span">My account</span>{" "}
                        <FontAwesomeIcon
                          icon={faUser}
                          className="common_icon"
                        />
                      </p>
                    </div>
                  )}

                  {isSignIn && (
                    <>
                      <div className="box_div border_box">
                        {/* <p className="title_text">My Cart</p> */}
                        <p
                          className="sub_text"
                          onClick={() => {
                            navigate.push("/product-cart");
                          }}
                        >
                          <span className="title_span">Cart</span>{" "}
                          <FontAwesomeIcon
                            icon={faCartShopping}
                            className={`common_icon ${
                              isActive === "/cart" ? "active" : ""
                            }`}
                          />
                        </p>
                      </div>

                      <div className="box_div">
                        {/* <p className="title_text">My Favourite</p> */}
                        <p
                          className="sub_text"
                          onClick={() => {
                            navigate.push("/wishlist");
                          }}
                        >
                          <span className="title_span">Wishlist</span>{" "}
                          <FontAwesomeIcon
                            icon={faHeart}
                            className={`common_icon ${
                              isActive === "/wishlist" ? "active" : ""
                            }`}
                          />
                        </p>
                      </div>

                      {/* <div className="box_div right_box"> */}
                        {/* <div
                          className="big_img_holder"
                          onClick={() => {
                            navigate.push("/wallet");
                          }}
                        >
                          <FontAwesomeIcon
                            icon={faWallet}
                            className={`big_icon ${
                              isActive === "/wallet" ? "active" : ""
                            }`}
                          />
                        </div> */}

                        {/* <div
                          className="big_img_holder bell_icon_holder"
                          onClick={goToNotificationsTab}
                        >
                          <FontAwesomeIcon
                            icon={faBell}
                            className={`big_icon ${
                              isActive === "" ? "active_class" : ""
                            }`}
                          />
                        </div> */}
                      {/* </div> */}
                    </>
                  )}
                </div>
              </div>
            </div>
          </div>
        </div>

        <div className="bottom_header">
          <div className="container">
            <div className="two_box_holder">
              <div className="box1">
                <Navbar
                  expand="lg"
                  expanded={expanded}
                  onToggle={() => setExpanded(!expanded)}
                >
                  <Navbar.Toggle aria-controls="basic-navbar-nav" />
                  <Navbar.Collapse id="basic-navbar-nav">
                    <Nav className="me-auto">
                      {navLinks.map((link) => (
                        <Nav.Link
                          key={link.path}
                          as={Link}
                          href={link.path}
                          active={isActive(link.path)}
                          onClick={() => setExpanded(false)}
                        >
                          {link.label}
                        </Nav.Link>
                      ))}
                    </Nav>
                  </Navbar.Collapse>
                </Navbar>
              </div>

              <div className="box2 ">
                <div className="common_icon_holder primary_theme_bg_colour">
                  <FontAwesomeIcon icon={faPhone} className="call_icon" />
                </div>
                <div className="text_holder">
                  <p className="first_text">Call To</p>
                  <p className="number_text">+91 {app_setup?.contact_no}</p>
                </div>

                {isSignIn && (
                  <div
                    className="common_icon_holder"
                    onClick={() => navigate.push("/account")}
                  >
                    <FontAwesomeIcon icon={faUser} className="call_icon" />
                  </div>
                )}
              </div>
            </div>
          </div>
        </div>

        {/* Offcanvas */}
        <Offcanvas show={false} onHide={() => {}} className="menu_offcanvas">
          <Offcanvas.Header closeButton />
          <Offcanvas.Body>
            <Navbar expand="lg">
              <Nav className="me-auto">
                {navLinks.map((link) => (
                  <Nav.Link
                    key={link.path}
                    as={Link}
                    href={link.path}
                    active={isActive(link.path)}
                  >
                    {link.label}
                  </Nav.Link>
                ))}
              </Nav>
            </Navbar>
          </Offcanvas.Body>
        </Offcanvas>
      </section>

      {/* <Use_Current_Location
        show={modalShow}
        onHide={() => setModalShow(false)}
        setShowConfimLocModal={setShowConfimLocModal}
      /> */}

      {/* <Current_Location_Offcanvas
        show={offCanvasShow}
        onHide={() => setOffCanvasShow(false)}
      /> */}

      <Login_Modal
        show={showLoginModal}
        onHide={() => {
          setShowLoginModal(false);
        }}
        setShowResetModal={() => setShowResetModal(true)}
        setShowAccountCreted={() => setShowAccountCreted(true)}
        setShowLogin={() => setShowLogin(true)}
      />

      <Reset_Password_Modal
        email={email}
        setEmail={setEmail}
        contact={contact}
        setContact={setContact}
        show={showResetModal}
        onHide={() => {
          setShowResetModal(false);
        }}
        setShowSetPassModal={() => setShowSetPassModal(true)}
      />

      <Set_New_Password_Modal
        email={email}
        setEmail={setEmail}
        contact={contact}
        setContact={setContact}
        show={showSetPassModal}
        onHide={() => {
          setShowSetPassModal(false);
        }}
        setShowSucsessModal={() => setShowSucsessModal(true)}
      />

      <Success_Modal
        show={showSuccessModal}
        onHide={() => {
          setShowSucsessModal(false);
        }}
        successText="Password Reseted Successfully!"
      />

      <Success_Modal
        show={showAccountCreted}
        onHide={() => {
          setShowAccountCreted(false);
        }}
        successText="Account Created Successful!"
      />

      <Success_Modal
        show={showLogin}
        onHide={() => {
          setShowLogin(false);
        }}
        successText="Login Successfully!"
      />
    </>
  );
}

export default Header;
