"use client";

import {
  faBars,
  faCartShopping,
  faHeart,
  faMagnifyingGlass,
  faUser,
  faChevronDown,
  faChevronRight,
} from "@fortawesome/free-solid-svg-icons";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import { useEffect, useRef, useState } from "react";
import { Form, InputGroup, Nav, Navbar, Offcanvas } from "react-bootstrap";
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 "./Header.css";
import { useDispatch, useSelector } from "react-redux";
import { getAllCart, postToLoginCart } from "../../features/cart/cartSlice";
import {
  allCurrency,
  appSetup,
  getAllSubCategory,
  setCurrentCurrency,
  SocialLink,
} from "../../features/master/masterSlice";
import { getAllWishlist } from "../../features/wishlist/wishlistSlice";
import Cookies from "js-cookie";
import Link from "next/link";
import { usePathname, useRouter } from "next/navigation";
import { getAllProducts } from "../../features/products/productsSlice";

function Header() {
  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 [offCanvasShow, setOffCanvasShow] = useState(false);
  const handleClose = () => setShowOffcanvas(false);
  const handleShow = () => setShowOffcanvas(true);
  const [searchTerm, setSearchTerm] = useState("");
  const [showSearchCanvas, setShowSearchCanvas] = useState(false);
  const [expanded, setExpanded] = useState(false);
  const [email, setEmail] = useState();
  const [contact, setContact] = useState();
  const [showCategories, setShowCategories] = useState(false);
  const [openCategory, setOpenCategory] = useState(null);
  const navigate = useRouter();
  //  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);
  const allcartData = useSelector((state) => state.cart.allCarts);
  const allWishlist = useSelector((state) => state.wishlist.allWishlist);
  const app_setup = useSelector((state) => state?.master?.app_setup);
  const categories = useSelector((state) => state.master.categories);
  const subcategories = useSelector((state) => state.master.subcategories);

  const handleCategoryHover = async (categoryId) => {
    const result = await dispatch(
      getAllSubCategory({
        category_id: categoryId,
      }),
    );

    const data = result?.payload?.data || result?.payload || [];

    if (data?.length > 0) {
      setOpenCategory(categoryId);
    } else {
      setOpenCategory(null);
    }
  };
  useEffect(() => {
    dispatch(allCurrency());
    dispatch(getAllCart(isSignin));
    dispatch(appSetup());
    dispatch(getAllWishlist());
    dispatch(getAllProducts());
    dispatch(SocialLink());
  }, [dispatch]);

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

  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 handleKeyPress = (e) => {
    if (e.key === "Enter" && searchTerm.trim() !== "") {
      navigate.push(`/shop`);
      // 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 handleSearchClick = () => {
    if (!searchTerm.trim()) return;

    let searches = JSON.parse(localStorage.getItem("recentSearches")) || [];

    searches = [
      searchTerm,
      ...searches.filter((item) => item !== searchTerm),
    ].slice(0, 5);

    localStorage.setItem("recentSearches", JSON.stringify(searches));
    setRecentSearches(searches);
    if (!searchTerm?.trim()) return;
    dispatch(
      getAllProducts({
        name: searchTerm,
      }),
    );
    setShowSearchCanvas(false);
    setShowRecent(false);
    setSearchTerm("");
    navigate.push(`/shop?search=${encodeURIComponent(searchTerm)}`);
  };

  const navLinks = [
    { path: "/", label: "Home" },
    { path: "/blog/", label: "Blogs" },
    { 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);
    }
  }, []);

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

  const handleRecentSearchClick = (item) => {
    dispatch(
      getAllProducts({
        name: item,
      }),
    );

    setShowRecent(false);
    setShowSearchCanvas(false);
    setSearchTerm("");

    navigate.push(`/shop?search=${encodeURIComponent(item)}`);
  };

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

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

    window.addEventListener("scroll", handleScroll);

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

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

  useEffect(() => {
    const handleOutsideClick = (event) => {
      const clickedInsideDesktop = desktopSearchRef.current?.contains(
        event.target,
      );

      const clickedInsideMobile = mobileSearchRef.current?.contains(
        event.target,
      );

      if (!clickedInsideDesktop && !clickedInsideMobile) {
        setShowRecent(false);
      }
    };

    document.addEventListener("mousedown", handleOutsideClick);

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

  const handleCategoryToggle = async (categoryId) => {
    if (openCategory === categoryId) {
      setOpenCategory(null);
      return;
    }
    setOpenCategory(categoryId);
    await dispatch(
      getAllSubCategory({
        category_id: categoryId,
      }),
    );
  };

  return (
    <>
      {" "}
      <section className="Header">
        <div className="top_headerrr">
          <div className="container d-flex justify-content-between">
            <span className="support_text emailsa">
              Support: {app_setup?.email}
            </span>
            <span className="support_text">
              Contact: {app_setup?.contact_no}
            </span>
          </div>
        </div>
        <div
          className={`top_headers_holder ${
            showStickyHeader ? "sticky-header" : ""
          }`}
        >
          <div className="middle_header">
            <div className="container">
              <div className="all_divs_holder">
                {/* Logo */}
                <div className="new-header-wrappr">
                  <div className="location-logo-wrapper">
                    <div
                      className="logo_div"
                      onClick={() => navigate.push("/")}
                    >
                      <img
                        src={process.env.NEXT_PUBLIC_IMG_URL + app_setup?.logo}
                        // src={"/assets/images/logo/logo.jpeg"}
                        className="logo_img"
                        alt="logo"
                      />
                    </div>{" "}
                  </div>
                  <div className="two_box_holder desktop-header">
                    <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> */}

                          <Nav className="me-auto">
                            <Nav.Link
                              as={Link}
                              href="/"
                              active={isActive("/")}
                              onClick={() => setExpanded(false)}
                            >
                              Home
                            </Nav.Link>

                            <div
                              className="category-menu-wrapper"
                              onMouseEnter={() => setShowCategories(true)}
                              onMouseLeave={() => {
                                setShowCategories(false);
                                setOpenCategory(null);
                              }}
                            >
                              <Link
                                href="/shop/"
                                className={`category-menu-btn ${
                                  currentPath === "/shop/" ? "active" : ""
                                }`}
                                onMouseEnter={() => setShowCategories(true)}
                              >
                                Categories
                                <FontAwesomeIcon
                                  icon={faChevronDown}
                                  className={`category-arrow ${
                                    showCategories ? "rotate" : ""
                                  }`}
                                />
                              </Link>

                              {showCategories && (
                                <div className="category-dropdown">
                                  {(categories?.data || categories || []).map(
                                    (item) => {
                                      const categorySubcategories =
                                        openCategory === item.id
                                          ? subcategories?.data ||
                                            subcategories ||
                                            []
                                          : [];

                                      const hasSubcategories =
                                        categorySubcategories.length > 0;

                                      return (
                                        <div
                                          className="category-dropdown-item"
                                          key={item.id}
                                          onMouseEnter={() =>
                                            handleCategoryHover(item.id)
                                          }
                                        >
                                          <div className="category-name">
                                            <Link
                                              href={`/shop?category_id=${item.id}&fromHeader=true`}
                                              className="category-link"
                                              onClick={() => {
                                                setShowCategories(false);
                                                setOpenCategory(null);
                                                setExpanded(false);
                                              }}
                                            >
                                              {item.name}
                                            </Link>

                                            {hasSubcategories && (
                                              <FontAwesomeIcon
                                                icon={faChevronRight}
                                                className="sub-category-arrow"
                                              />
                                            )}
                                          </div>

                                          {openCategory === item.id &&
                                            hasSubcategories && (
                                              <div className="subcategory-dropdown">
                                                {categorySubcategories.map(
                                                  (subCategory) => (
                                                    <Link
                                                      key={subCategory.id}
                                                      href={`/shop-subcategory?category_id=${item.id}&sub_category_id=${subCategory.id}`}
                                                      className="subcategory-item"
                                                      onClick={() => {
                                                        setShowCategories(
                                                          false,
                                                        );
                                                        setOpenCategory(null);
                                                        setExpanded(false);
                                                      }}
                                                    >
                                                      {subCategory.name}
                                                    </Link>
                                                  ),
                                                )}
                                              </div>
                                            )}
                                        </div>
                                      );
                                    },
                                  )}
                                </div>
                              )}
                            </div>

                            {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>
                </div>
                <div className="new-header-wrappr">
                  <div className="search_offcanvas d-none d-md-block">
                    <div
                      className="search_input_div mobile-searc container"
                      ref={desktopSearchRef}
                    >
                      <InputGroup>
                        <Form.Control
                          placeholder="Search Product"
                          type="search"
                          value={searchTerm}
                          onChange={(e) => setSearchTerm(e.target.value)}
                          // onKeyDown={handleKeyPress}
                          onKeyDown={(e) => {
                            if (e.key === "Enter") {
                              handleSearchClick();
                            }
                          }}
                          onFocus={() => setShowRecent(true)}
                        />
                        <InputGroup.Text
                          onClick={handleSearchClick}
                          style={{ cursor: "pointer" }}
                        >
                          <FontAwesomeIcon icon={faMagnifyingGlass} />
                        </InputGroup.Text>
                      </InputGroup>

                      {showRecent && recentSearches.length > 0 && (
                        <div className="recent-search-list">
                          <h6>Recent Searches</h6>
                          <div className="list-wrapper">
                            {recentSearches.map((item, index) => (
                              <div
                                key={index}
                                className="recent-search-item"
                                // onClick={() => {
                                //   setSearchTerm(item);
                                //   setShowRecent(false);
                                // }}
                                onClick={() => handleRecentSearchClick(item)}
                              >
                                {item}
                              </div>
                            ))}
                          </div>
                        </div>
                      )}
                    </div>
                  </div>
                  <div className="search-wrapper">
                    <div className="three_box_div ">
                      <div className="box_div border_box">
                        <p
                          className="sub_text"
                          onClick={() => {
                            navigate.push("/product-cart");
                          }}
                        >
                          <div className="icon_holder">
                            {allcartData?.data?.length > 0 && (
                              <div
                                className="counter-div"
                                onClick={() => {
                                  navigate.push("/product-cart");
                                }}
                              >
                                {allcartData?.data?.length || 0}
                              </div>
                            )}

                            <FontAwesomeIcon
                              icon={faCartShopping}
                              className={`common_ico header-icons ${
                                isActive === "/cart" ? "active" : ""
                              }`}
                            />
                          </div>
                          cart
                        </p>
                      </div>
                      {!isSignin && (
                        <>
                          <div className="box_div border_box new_login_box">
                            <div
                              className=""
                              onClick={() => {
                                setShowLoginModal(true);
                              }}
                            >
                              <p className="sub_text">
                                {" "}
                                <FontAwesomeIcon
                                  icon={faUser}
                                  className={`common_ico header-icons`}
                                />
                                Login
                              </p>
                            </div>
                          </div>
                        </>
                      )}
                      {isSignin && (
                        <>
                          <div className="box_div">
                            <p
                              className="sub_text"
                              onClick={() => {
                                navigate.push("/wishlist");
                              }}
                            >
                              <div className="icon_holder">
                                {allWishlist?.data?.length > 0 && (
                                  <div
                                    className="counter-div"
                                    onClick={() => {
                                      navigate.push("/wishlist");
                                    }}
                                  >
                                    {allWishlist?.data?.length || 0}
                                  </div>
                                )}
                                <FontAwesomeIcon
                                  icon={faHeart}
                                  className={`common_icon  header-icons ${
                                    isActive === "/wishlist" ? "active" : ""
                                  }`}
                                />
                              </div>
                              wishlist
                            </p>
                          </div>

                          {isSignin && (
                            <div className="box_div">
                              <div
                                className=""
                                onClick={() => navigate.push("/account")}
                              >
                                <p className="sub_text">
                                  {" "}
                                  <FontAwesomeIcon
                                    icon={faUser}
                                    className={`common_ico header-icons`}
                                  />
                                  Account
                                </p>
                              </div>
                            </div>
                          )}
                        </>
                      )}
                      <div
                        className="menu-bar  header-icons "
                        onClick={handleShow}
                      >
                        <FontAwesomeIcon icon={faBars} />
                      </div>
                    </div>
                  </div>
                </div>
              </div>{" "}
              <div className="search_offcanvas d-block d-md-none">
                <div
                  className="search_input_div mobile-searc container"
                  ref={mobileSearchRef}
                >
                  <InputGroup>
                    <Form.Control
                      placeholder="Search Product"
                      value={searchTerm}
                      type="search"
                      onChange={(e) => setSearchTerm(e.target.value)}
                      // onKeyDown={handleKeyPress}
                      onKeyDown={(e) => {
                        if (e.key === "Enter") {
                          handleSearchClick();
                        }
                      }}
                      onFocus={() => setShowRecent(true)}
                    />
                    <InputGroup.Text
                      onClick={handleSearchClick}
                      style={{ cursor: "pointer" }}
                    >
                      <FontAwesomeIcon icon={faMagnifyingGlass} />
                    </InputGroup.Text>
                  </InputGroup>

                  {showRecent && recentSearches.length > 0 && (
                    <div className="recent-search-list">
                      <h6>Recent Searches</h6>
                      <div className="list-wrapper">
                        {recentSearches.map((item, index) => (
                          <div
                            key={index}
                            className="recent-search-item"
                            onClick={() => handleRecentSearchClick(item)}
                          >
                            {item}
                          </div>
                        ))}
                      </div>
                    </div>
                  )}
                </div>
              </div>
            </div>
          </div>
        </div>{" "}
        <Offcanvas
          show={showOffcanvas}
          onHide={handleClose}
          placement="start"
          className="menu_offcanvas"
        >
          <Offcanvas.Header closeButton>
            <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>
          </Offcanvas.Header>

          <Offcanvas.Body>
            <Nav className="flex-column">
              <Nav.Link
                as={Link}
                href="/"
                active={isActive("/")}
                onClick={() => {
                  handleClose();
                  setExpanded(false);
                }}
              >
                Home
              </Nav.Link>

              <div className="mobile-category">
                <div className="mobile-category-header">
                  <Link
                    href="/shop/"
                    onClick={handleClose}
                    className={
                      currentPath === "/shop/"
                        ? "active-nav mobile-category-link"
                        : "mobile-category-link"
                    }
                  >
                    Categories
                  </Link>

                  <button
                    type="button"
                    className="mobile-category-toggle"
                    onClick={() => {
                      setShowCategories((prev) => !prev);
                      setOpenCategory(null);
                    }}
                  >
                    <FontAwesomeIcon
                      icon={faChevronDown}
                      className={showCategories ? "rotate" : ""}
                    />
                  </button>
                </div>

                {showCategories && (
                  <div className="mobile-category-dropdown">
                    {(categories?.data || categories || []).map((item) => {
                      const isOpen = openCategory === item.id;

                      const categorySubcategories = isOpen
                        ? subcategories?.data || subcategories || []
                        : [];

                      return (
                        <div key={item.id} className="mobile-category-item">
                          {/* Category Row */}
                          <div className="mobile-category-name">
                            <Link
                              href={`/shop?category_id=${item.id}&fromHeader=true`}
                              onClick={handleClose}
                            >
                              {item.name}
                            </Link>

                            <button
                              type="button"
                              className="mobile-subcategory-toggle"
                              onClick={(e) => {
                                e.preventDefault();
                                e.stopPropagation();
                                handleCategoryToggle(item.id);
                              }}
                            >
                              <FontAwesomeIcon
                                icon={faChevronDown}
                                className={isOpen ? "rotate" : ""}
                              />
                            </button>
                          </div>

                          {isOpen && categorySubcategories.length > 0 && (
                            <div className="mobile-subcategory">
                              {categorySubcategories.map((subCategory) => (
                                <Link
                                  key={subCategory.id}
                                  href={`/shop-subcategory?category_id=${item.id}&sub_category_id=${subCategory.id}`}
                                  onClick={handleClose}
                                >
                                  {subCategory.name}
                                </Link>
                              ))}
                            </div>
                          )}
                        </div>
                      );
                    })}
                  </div>
                )}
              </div>
              {navLinks.slice(1).map((link) => (
                <Nav.Link
                  key={link.path}
                  as={Link}
                  href={link.path}
                  active={isActive(link.path)}
                  onClick={() => {
                    handleClose();
                    setExpanded(false);
                  }}
                >
                  {link.label}
                </Nav.Link>
              ))}
            </Nav>
          </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!"
      />
    </>
  );
}

export default Header;
