import { Badge, Fab } from "@mui/material";
import ShoppingCartOutlinedIcon from "@mui/icons-material/ShoppingCartOutlined";
import { useAppDispatch, useAppSelector } from "../../app/redux/hooks";
import CustomDialog from "../components/custom/dialog";
import { ShopingCart } from "../view/public/shopping/cart/shopinCart";
import { useEffect, useRef, useState } from "react";
import { useNavigate } from "react-router-dom";
import { getAboutUsAsync } from "../../app/slices/footerSlice/footerSlice";
import { showSnackbar } from "../../app/slices/common/customSnackBar/customSnackbarSlice";
import { getDecryptedToken } from "../../app/auth/authHandler";
import { setProfilesection } from "../../app/slices/common/locationSlice/locationSlice";
import { ChatPage } from "../view/public/Chatbot";
import { LinkedIn, YouTube } from "@mui/icons-material";
export const Footer = () => {
  const { addTocart } = useAppSelector((state) => state.CartState);
  const cartCount = addTocart?.data?.length || 0;
  const [modalType, setModalType] = useState("");
  //  const [aboutUs, setAboutUs] = useState<any>("");
  const [isChatOpen, setIsChatOpen] = useState(false);
  const chatPanelRef = useRef<HTMLDivElement>(null);
  const navigate = useNavigate();
  const dispatch = useAppDispatch();
  const { isValidUser }: any = useAppSelector((state) => state.ProfileState);
  const aboutUs = useAppSelector(
    (state) => state.FooterDataState.aboutUs?.data
  );
  const hasFetched = useRef(false);
  const onOpenModal = (type: string) => {
    setModalType(type);
  };
  const onCloseModal = () => {
    setModalType("");
  };
  const hasValue = (obj: any) => {
    if (!obj) return false;

    return Object.values(obj).some((val) => {
      if (typeof val === "string") return val.trim() !== "";
      if (typeof val === "object" && val !== null) {
        return Object.values(val).some(
          (subVal) => typeof subVal === "string" && subVal.trim() !== ""
        );
      }
      return false;
    });
  };

  useEffect(() => {
    if (hasFetched.current) return;
    hasFetched.current = true;
    if (!hasValue(aboutUs)) {
      dispatch(getAboutUsAsync());
    }
  }, [aboutUs, dispatch]);

  // useEffect(() => {
  //    dispatch(getAboutUsAsync())
  //   .then((response: any) => {
  //     setAboutUs(response?.payload?.data);
  //   });
  // }, []);
  useEffect(() => {
    const handleClickOutside = (event: MouseEvent) => {
      if (
        isChatOpen &&
        chatPanelRef.current &&
        !chatPanelRef.current.contains(event.target as Node) // Type assertion for event.target
      ) {
        setIsChatOpen(false); // Close the chat panel
      }
    };

    // Add event listener for clicks
    document.addEventListener("mousedown", handleClickOutside);

    // Cleanup the event listener on component unmount
    return () => {
      document.removeEventListener("mousedown", handleClickOutside);
    };
  }, [isChatOpen]);

  const handleNavigateToWishList = () => {
    const accessToken = getDecryptedToken();
    if (accessToken) {
      dispatch(setProfilesection("Wishlist"));
      navigate("/profile");
    } else {
      dispatch(
        showSnackbar({
          message: "Please login to see your wishlist",
          severity: "error",
          autoHide: 2000,
        })
      );
    }
  };
  const handleNavigateToAccount = () => {
    const accessToken = getDecryptedToken();
    if (accessToken) {
      dispatch(setProfilesection("AccountDetails"));
      navigate("/profile");
    } else {
      dispatch(
        showSnackbar({
          message: "Please login to see your account",
          severity: "error",
          autoHide: 2000,
        })
      );
    }
  };
  const handleChatPage = () => {
    if (isValidUser) {
      setIsChatOpen((prev) => !prev); // Toggle chat visibility
    } else {
      dispatch(
        showSnackbar({
          message: "Please sign in to access the chat feature.",
          severity: "error",
          autoHide: 2000,
        })
      );
    }
  };

  return (
    <>
      {" "}
      <footer id="footer" className="footer background-gray md-pb-70">
        <div className="footer-wrap">
          <div className="footer-body">
            <div className="container">
              <div className="row">
                <div className="col-xl-3 col-md-6 col-12">
                  <div className="footer-infor">
                    <div className="footer-logo">
                      <a href="index.html">
                        <img src="/images/Web-Logo.png" alt="" />
                      </a>
                    </div>
                    <ul>
                      <li>
                        <p>
                          Address: CollabKart Ernakulam, Kerala,
                          India-683572{" "}
                        </p>
                      </li>
                      <li>
                        <p>
                          Email: <span>support@collabkart.com</span>
                        </p>
                      </li>
                      <li>
                        <p>
                          Phone:{" "}
                          <span>
                            +91 96501 98806
                          </span>
                        </p>
                      </li>
                    </ul>
                    <a
                      style={{ marginBottom: "28px" }}
                      className="tf-btn btn-line"
                      onClick={() => {
                        navigate("/store-locations");
                      }}
                    >
                      Get direction
                      <i className="icon icon-arrow1-top-left"></i>
                    </a>
                    <ul className="tf-social-icon d-flex gap-10">
                      <li>
                        <a
                          href="https://www.facebook.com/navyabakeshop"
                          target="_blank"
                          rel="noopener noreferrer"
                          className="box-icon w_34 round social-facebook social-line"
                        >
                          <i className="icon fs-14 icon-fb"></i>
                        </a>
                      </li>
                      <li>
                        <a
                          href="https://www.threads.com/@navyabakeshop"
                          target="_blank"
                          rel="noopener noreferrer"
                          className="box-icon w_34 round social-twiter social-line"
                        >
                          <i className="icon fs-12 icon-Icon-x"></i>
                        </a>
                      </li>
                      <li>
                        <a
                          href="https://www.instagram.com/navyabakeshop/"
                          target="_blank"
                          rel="noopener noreferrer"
                          className="box-icon w_34 round social-instagram social-line"
                        >
                          <i className="icon fs-14 icon-instagram"></i>
                        </a>
                      </li>
                      <li>
                        <a
                          href="https://www.linkedin.com/company/navya-bake-shop/"
                          target="_blank"
                          rel="noopener noreferrer"
                          className="box-icon w_34 round social-linkedin social-line"
                        >
                          <LinkedIn sx={{ fontSize: "1.2rem" }} />
                        </a>
                      </li>
                      <li>
                        <a
                          href="https://www.youtube.com/@navyabakeshop"
                          target="_blank"
                          rel="noopener noreferrer"
                          className="box-icon w_34 round social-youtube social-line"
                        >
                          <YouTube sx={{ fontSize: "1.2rem" }} />
                        </a>
                      </li>
                    </ul>
                  </div>
                </div>
                <div className="col-xl-3 col-md-6 col-12 footer-col-block">
                  <div className="footer-heading footer-heading-desktop">
                    <h6>Help</h6>
                  </div>
                  <div className="footer-heading footer-heading-moblie">
                    <h6>Help</h6>
                  </div>
                  <ul className="footer-menu-list tf-collapse-content">
                    <li>
                      <a
                        className="footer-menu_item"
                        onClick={() => {
                          navigate("/privacy-policy");
                        }}
                      >
                        Privacy Policy
                      </a>
                    </li>
                    {/* <li>
                      <span className="footer-menu_item">
                        {" "}
                        Returns + Exchanges{" "}
                      </span>
                    </li> */}
                    {/* <li>
                      <span className="footer-menu_item">Shipping</span>
                    </li> */}
                    <li>
                      <a
                        className="footer-menu_item"
                        onClick={() => {
                          navigate("/terms-conditions");
                        }}
                      >
                        Terms &amp; Conditions
                      </a>
                    </li>
                    <li>
                      <a
                        className="footer-menu_item"
                        onClick={() => {
                          navigate("/faq");
                        }}
                      >
                        FAQ’s
                      </a>
                    </li>
                    {/* <li>
                      <span className="footer-menu_item">Compare</span>
                    </li> */}
                    <li>
                      <a
                        className="footer-menu_item"
                        onClick={() => {
                          handleNavigateToAccount();
                        }}
                      >
                        Account
                      </a>
                    </li>
                    <li>
                      <a
                        className="footer-menu_item"
                        onClick={() => {
                          handleNavigateToWishList();
                        }}
                      >
                        My Wishlist
                      </a>
                    </li>
                        <li>
                      <a
                        className="footer-menu_item"
                        onClick={() => {
                          navigate("/cancellation-refund-policy");
                        }}
                      >
                        Cancellation and Refund Policy
                      </a>
                    </li>
                  </ul>
                </div>
                {/* <div className="col-xl-3 col-md-6 col-12 footer-col-block">
                  <div className="footer-heading footer-heading-desktop">
                    <h6>About us</h6>
                  </div>
                  <div className="footer-heading footer-heading-moblie">
                    <h6>About us</h6>
                  </div>
                  <ul className="footer-menu-list tf-collapse-content">
                    <li>
                      <a
                        className="footer-menu_item"
                        onClick={() => {
                          navigate("/aboutUs");
                        }}
                      >
                        Our Story
                      </a>
                    </li>
                    <li>
                      <a
                        className="footer-menu_item"
                        onClick={() => {
                          navigate("/store-locations");
                        }}
                      >
                        Visit Our Store
                      </a>
                    </li>
                    <li>
                      <a
                        className="footer-menu_item"
                        onClick={() => {
                          navigate("/cancellation-refund-policy");
                        }}
                      >
                        Cancellation and Refund Policy
                      </a>
                    </li> */}
                    {/* <li>
                      <span className="footer-menu_item">Contact Us</span>
                    </li> */}
                  {/* </ul>
                </div> */}
                {/* <div className="col-xl-3 col-md-6 col-12">
                  <div className="footer-newsletter footer-col-block">
                    <div className="footer-heading footer-heading-desktop">
                      <h6>Subscribe</h6>
                    </div>
                    <div className="footer-heading footer-heading-moblie">
                      <h6>Subscribe</h6>
                    </div>
                    <div className="tf-collapse-content">
                      <div className="footer-menu_item">
                        Sign up to get first dibs on new arrivals, sales,
                        exclusive content, events and more!
                      </div>
                      <form
                        className="form-newsletter"
                        id="subscribe-form"
                        action="#"
                        method="post"
                        acceptCharset="utf-8"
                        data-mailchimp="true"
                      >
                        <div id="subscribe-content">
                          <fieldset className="email">
                            <input
                              type="email"
                              name="email-form"
                              id="subscribe-email"
                              placeholder="Enter your email...."
                              tabIndex={0}
                              aria-required="true"
                            />
                          </fieldset>
                          <div className="button-submit">
                            <button
                              id="subscribe-button"
                              className="tf-btn btn-sm radius-3 btn-fill btn-icon animate-hover-btn"
                              type="button"
                            >
                              Subscribe
                              <i className="icon icon-arrow1-top-left"></i>
                            </button>
                          </div>
                        </div>
                        <div id="subscribe-msg"></div>
                      </form>
                    </div>
                  </div>
                </div> */}
                <div className="col-xl-3 col-md-6 col-12">
                  <div className="footer-newsletter footer-col-block">
                    <div className="footer-heading footer-heading-desktop">
                      <h6>App Download</h6>
                    </div>
                    <div className="footer-heading footer-heading-moblie">
                      <h6>App Download</h6>
                    </div>
                    <div className="tf-collapse-content">
                      <div className="footer-menu_item">
                        Download CollabKart app{" "}
                      </div>
                      <a
                        onClick={() => {
                          window.location.href =
                            aboutUs?.data?.app_url?.appstore_link;
                        }}
                      >
                        <img
                          src="/images/app-store.svg"
                          className="mt-2"
                          width="125"
                          alt=""
                        />
                      </a>
                      <a
                        onClick={() => {
                          window.location.href =
                            aboutUs?.data?.app_url?.playstore_link;
                        }}
                      >
                        <img
                          src="/images/play-store.svg"
                          className="mt-2"
                          width="125"
                          alt=""
                        />
                      </a>
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
          <div className="footer-bottom">
            <div className="container">
              <div className="row">
                <div className="col-12">
                  <div className="footer-bottom-wrap d-flex gap-20 flex-wrap justify-content-between align-items-center">
                    <div className="footer-menu_item">
                      © 2026 CollabKart. All Rights Reserved
                    </div>
                    <div className="tf-payment">
                      <img src="/images/payments/visa.png" alt="" />
                      <img src="/images/payments/img-1.png" alt="" />
                      <img src="/images/payments/img-2.png" alt="" />
                      <img src="/images/payments/img-3.png" alt="" />
                      <img src="/images/payments/img-4.png" alt="" />
                    </div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>
      </footer>{" "}
      <div
        onClick={handleChatPage}
        className="chat-button"
        style={{
          position: "fixed",
          bottom: "20px",
          right: "98px",
          zIndex: 1000,
        }}
      >
        <img
          src="/images/Mobile.png"
          alt="Chat"
          style={{
            width: "30px",
            height: "30px",
            borderRadius: "50%",
            backgroundColor: "#fff",
            padding: "4px",
          }}
        />
        <span style={{ fontWeight: 500, marginLeft: "5px" }}>Let's Chat!</span>
      </div>
      <Fab
        color="primary"
        aria-label="add"
        style={{
          position: "fixed",
          bottom: "20px",
          right: "20px",
          zIndex: 1000,
        }}
        onClick={() => onOpenModal("shopingCart")}
      >
        <Badge badgeContent={cartCount} color="warning">
          <ShoppingCartOutlinedIcon />
        </Badge>
      </Fab>
      {modalType === "shopingCart" && (
        <CustomDialog
          component={<ShopingCart onClose={onCloseModal} />}
          title="Shopping Cart"
          openDialog={modalType === "shopingCart"}
          handleCloseDialog={onCloseModal}
          modalPlace="right"
        />
      )}
      <div
        ref={chatPanelRef} // Attach ref to the chat panel
        className={`chat-panel ${isChatOpen ? "open" : ""}`}
        style={{
          position: "fixed",
          top: "1rem",
          right: isChatOpen ? 0 : "-400px", // Slide in/out (adjust width as needed)
          width: "370px",
          height: "550px",
          zIndex: 1100,
          borderRadius: "15px",
          transition: "right 0.3s ease-in-out", // Smooth sliding animation
          backgroundColor: "#fff", // Ensure background is visible
          boxShadow: isChatOpen ? "-4px 0 8px rgba(0,0,0,0.2)" : "none", // Optional shadow
        }}
      >
        <ChatPage />
      </div>
    </>
  );
};
