"use client";
import {
  Navbar,
  Container,
  Nav,
  Offcanvas,
  Badge,
  OverlayTrigger,
  Tooltip,
  InputGroup,
  Dropdown,
} from "react-bootstrap";
import {
  faBagShopping,
  faBars,
  faBell,
  faBoxOpen,
  faCaretDown,
  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 Cookies from "js-cookie";
import { getAllCart, postToLoginCart } from "../../features/cart/cartSlice";
import {
  allCurrency,
  appSetup,
  getAllChildCategory,
  getAllSubCategory,
  setCurrentCurrency,
  SocialLink,
} from "../../features/master/masterSlice";
import { getAllWishlist } from "../../features/wishlist/wishlistSlice";

import { usePathname, useRouter } from "next/navigation";
import Link from "next/link";
import { getAllProducts } from "../../features/products/productsSlice";
import Logout_Modal from "../common-components/common_modal/logout_modal/Logout_Modal";
import { encodeId } from "../../utils/common";

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() !== "") {
      e.preventDefault();
      handleSearchClick();
    }
  };

  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 = (searchTerm) => {
    const searchValue = searchTerm.trim();

    if (!searchValue) return;

    dispatch(
      getAllProducts({
        name: searchValue,
      }),
    );
    setShowRecent(true);
  };
  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: "/blog/", label: "Blog" },
    { path: "/about-us/", label: "About Us" },
    { path: "/contact-us/", label: "Contact Us" },
  ];

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

    if (value.length === 0) {
      setShowRecent(false);

      return;
    }

    handleSearchClick(value);
  }, [searchTerm]);

  const [recentSearches, setRecentSearches] = useState([]);
  const [showRecent, setShowRecent] = useState(false);
  useEffect(() => {
    const searches = JSON.parse(localStorage.getItem("recentSearches")) || [];
    setRecentSearches(searches);
  }, []);

  const desktopSearchRef = useRef(null);
  const mobileSearchRef = useRef(null);

  useEffect(() => {
    const handleClickOutside = (event) => {
      if (
        desktopSearchRef.current &&
        desktopSearchRef.current.contains(event.target)
      ) {
        return;
      }

      if (
        mobileSearchRef.current &&
        mobileSearchRef.current.contains(event.target)
      ) {
        return;
      }
      setShowRecent(false);
    };

    document.addEventListener("mousedown", handleClickOutside);

    return () => document.removeEventListener("mousedown", handleClickOutside);
  }, []);

  const category = useSelector((state) => state.master.categories);
  const subcategories = useSelector((state) => state.master.subcategories);
  const childCategories = useSelector((state) => state.master.childcategories);
  const [headerSubcategories, setHeaderSubcategories] = useState([]);
  const [headerChildCategories, setHeaderChildCategories] = useState([]);
  const [hoverCategory, setHoverCategory] = useState(null);
  const [hoverSubCategory, setHoverSubCategory] = useState(null);
  const handleCategoryHover = async (catId) => {
    setHoverCategory(catId);

    await dispatch(
      getAllSubCategory({
        category_id: catId,
      }),
    );
  };

  const handleSubCategoryHover = async (subId) => {
    setHoverSubCategory(subId);

    await dispatch(
      getAllChildCategory({
        subcategory_id: subId,
      }),
    );
  };

  const [showStickyHeader, setShowStickyHeader] = useState(false);

  useEffect(() => {
    const handleScroll = () => {
      setShowStickyHeader(window.scrollY > 100);
    };

    window.addEventListener("scroll", handleScroll);

    return () => window.removeEventListener("scroll", handleScroll);
  }, []);

  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">
                    Need help? Call: <span> +91 {app_setup?.contact_no}</span>
                  </p>
                </div>
                <div className="top_header_col1 login-holder">
                  {" "}
                  {!isSignIn && (
                    <>
                      <p
                        className="content_html"
                        onClick={() => {
                          setShowLoginModal(true);
                        }}
                      >
                        Signup
                      </p>
                      |
                      <p
                        className="content_html"
                        onClick={() => {
                          setShowLoginModal(true);
                        }}
                      >
                        {" "}
                        Login
                      </p>
                    </>
                  )}
                  {isSignIn && (
                    <>
                      <p
                        className="content_html"
                        onClick={() => navigate.push("/account")}
                      >
                        My Account
                      </p>
                      |
                      <p
                        className="content_html"
                        onClick={() => setshowLogoutModal(true)}
                      >
                        Logout
                      </p>
                    </>
                  )}
                </div>
              </div>
            </div>
          </div> */}

          <div className="middle_header">
            <div className="container">
              <div className="all_divs_holder">
                <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="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">
                        <Nav.Link
                          as={Link}
                          href={navLinks[0].path}
                          active={isActive(navLinks[0].path)}
                          onClick={() => setExpanded(false)}
                        >
                          {navLinks[0].label}
                        </Nav.Link>

                        <div className="category_dropdown">
                          <Nav.Link
                            as={Link}
                            href="/shop"
                            className="d-none d-lg-flex"
                          >
                            Category
                            <span>
                              <FontAwesomeIcon icon={faCaretDown} />
                            </span>
                          </Nav.Link>

                          <div className="mega_menu">
                            {category?.map((cat) => (
                              <div
                                key={cat.id}
                                className="menu_item"
                                onMouseEnter={() => handleCategoryHover(cat.id)}
                              >
                                <Link
                                  href={`/shop?category_id=${cat.id}&fromHeader=true`}
                                  className="menu_link"
                                >
                                  {cat.name}
                                </Link>
                                <span>›</span>

                                {hoverCategory === cat.id && (
                                  <div className="submenu">
                                    {subcategories?.map((sub) => (
                                      <div
                                        key={sub.id}
                                        className="menu_item"
                                        onMouseEnter={() =>
                                          handleSubCategoryHover(sub.id)
                                        }
                                      >
                                        <Link
                                          href={`/shop?category_id=${cat.id}&subcategory_id=${sub.id}`}
                                          className="menu_link"
                                        >
                                          {sub.name}{" "}
                                        </Link>

                                        <span>›</span>

                                        {hoverSubCategory === sub.id && (
                                          <div className="child_menu">
                                            {childCategories?.map((child) => (
                                              <Link
                                                key={child.id}
                                                href={`/shop?category_id=${cat.id}&subcategory_id=${sub.id}&childcategory_id=${child.id}`}
                                              >
                                                {child.name}
                                              </Link>
                                            ))}
                                          </div>
                                        )}
                                      </div>
                                    ))}
                                  </div>
                                )}
                              </div>
                            ))}
                          </div>
                        </div>
                        <Nav.Link
                          as={Link}
                          href="/shop"
                          className="d-lg-none"
                          onClick={() => setExpanded(false)}
                        >
                          Category
                        </Nav.Link>
                        {navLinks.slice(1).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="search_input_div  desktop-search mobile-searc "
                  ref={desktopSearchRef}
                >
                  <InputGroup>
                    <Form.Control
                      placeholder="Search Product"
                      value={searchTerm}
                      onChange={(e) => setSearchTerm(e.target.value)}
                      onKeyDown={handleKeyPress}
                    />
                    <InputGroup.Text
                      onClick={() => handleSearchClick(searchTerm)}
                      style={{ cursor: "pointer" }}
                    >
                      <FontAwesomeIcon icon={faMagnifyingGlass} />
                    </InputGroup.Text>
                  </InputGroup>

                  {showRecent && (
                    <div className="recent-search-list">
                      <div className="list-wrapper">
                        {getallproduct?.data?.length > 0 ? (
                          getallproduct.data.map((item, index) => (
                            <div
                              key={index}
                              className="recent-search-item"
                              onClick={() => {
                                setSearchTerm(item?.name);
                                setShowRecent(false);

                                navigate.push(
                                  `/product-details/${encodeId(item?.id)}?search=${encodeURIComponent(item?.name)}`,
                                );
                              }}
                            >
                              {item?.name}
                            </div>
                          ))
                        ) : (
                          <div className="text-center py-3 text-muted">
                            <div style={{ fontSize: "30px" }}>🔍</div>
                            <div>No results found</div>
                          </div>
                        )}
                      </div>
                    </div>
                  )}
                </div>

                <div className="three_box_div ">
                  {isSignIn && (
                    <>
                      <div className="box_div">
                        <div
                          className="sub_text icon-holder"
                          onClick={() => {
                            navigate.push("/wishlist");
                          }}
                        >
                          {allWishlist?.data?.length > 0 && (
                            <div className="count_div ">
                              <span className="count_text">
                                {allWishlist?.data?.length}
                              </span>
                            </div>
                          )}
                          <FontAwesomeIcon
                            icon={faHeart}
                            className={`common_icon ${
                              isActive === "/wishlist" ? "active" : ""
                            }`}
                          />
                        </div>
                      </div>
                    </>
                  )}
                  <div className="box_div border_box">
                    <div
                      className="sub_text  icon-holder"
                      onClick={() => {
                        navigate.push("/product-cart");
                      }}
                    >
                      {allcartData?.data?.length > 0 && (
                        <div className="count_div ">
                          <span className="count_text">
                            {allcartData?.data?.length}
                          </span>
                        </div>
                      )}
                      <FontAwesomeIcon
                        icon={faCartShopping}
                        className={`common_icon ${
                          isActive === "/cart" ? "active" : ""
                        }`}
                      />
                    </div>
                  </div>
                  {!isSignIn && (
                    <>
                      <button
                        type="button"
                        className="header_login_btn"
                        onClick={() => {
                          setShowLoginModal(true);
                        }}
                      >
                        <FontAwesomeIcon icon={faUser} />
                        <span>Login</span>
                      </button>
                    </>
                  )}
                  {isSignIn && (
                    <>
                      <div className="box_div border_box">
                        <div
                          className="sub_text  icon-holder"
                          onClick={() => navigate.push("/account")}
                        >
                          <FontAwesomeIcon
                            icon={faUser}
                            className={`common_icon ${
                              isActive === "/account" ? "active" : ""
                            }`}
                          />
                        </div>
                      </div>
                    </>
                  )}
                </div>
              </div>

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

                {showRecent && (
                  <div className="recent-search-list">
                    <div className="list-wrapper">
                      {getallproduct?.data?.length > 0 ? (
                        getallproduct.data.map((item, index) => (
                          <div
                            key={index}
                            className="recent-search-item"
                            onClick={() => {
                              setSearchTerm(item?.name);
                              setShowRecent(false);

                              navigate.push(
                                `/product-details/${encodeId(item?.id)}?search=${encodeURIComponent(item)}`,
                              );
                            }}
                          >
                            {item?.name}
                          </div>
                        ))
                      ) : (
                        <div className="text-center py-3 text-muted">
                          <div style={{ fontSize: "30px" }}>🔍</div>
                          <div>No results found</div>
                        </div>
                      )}
                    </div>
                  </div>
                )}
              </div>
            </div>
          </div>
        </div>

        <Offcanvas
          show={expanded}
          onHide={() => setExpanded(false)}
          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>

      <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!"
      />

      <Logout_Modal
        show={showLogoutModal}
        onHide={() => setshowLogoutModal(false)}
      />
    </>
  );
}

export default Header;
