import React, { useState, useEffect, useRef } from "react";
import {
  AddOfferButton,
  AuthButtonsContainer,
  EndIcon,
  // FilterContainer,
  // FilterIcon,
  HeaderContainer,
  LoginButton,
  LogoContainer,
  RegisterButton,
  SearchIcon,
  SearchInput,
  SearchInputMobile,
  ToggleDrawerButton,
  ToolsButtonsContainer,
  ToolsContainer,
  UserButton,
  UserName,
} from "./Header.styled";
import PropTypes from "prop-types";
import { AppBar, Badge, Toolbar, useMediaQuery } from "@mui/material";
import { useTheme } from "@mui/system";
import MenuOutlinedIcon from "@mui/icons-material/MenuOutlined";
import MailIcon from "@mui/icons-material/EmailOutlined";
import Autorenew from "@mui/icons-material/Autorenew";
import AccountCircle from "@mui/icons-material/PersonOutlineOutlined";
import Drawer from "../MUI/DrawerComponent";
import PopoverComponent from "../Popovers/PopoverComponent";
import { MyPosts } from "../Popovers/MyPosts/MyPosts";
import { MyMessages } from "../Popovers/MyMessages/MyMessages";
import { MyProfile } from "../Popovers/MyProfile/MyProfile";
import { ReactComponent as LogoHorizontal } from "../../assets/images/svg/logo-horizontal.svg";
import selectedTheme from "../../themes";
import { useTranslation } from "react-i18next";
import { IconButton } from "../Buttons/IconButton/IconButton";
import { useDispatch, useSelector } from "react-redux";
import { selectUserId } from "../../store/selectors/loginSelectors";
import { selectProfileName } from "../../store/selectors/profileSelectors";
import { useHistory, useRouteMatch } from "react-router-dom";
import {
  BASE_PAGE,
  FORGOT_PASSWORD_MAIL_SENT,
  FORGOT_PASSWORD_PAGE,
  HOME_PAGE,
  LOGIN_PAGE,
  REGISTER_PAGE,
  REGISTER_SUCCESSFUL_PAGE,
  RESET_PASSWORD_PAGE,
} from "../../constants/pages";
// import { convertQueryStringForFrontend } from "../../util/helpers/queryHelpers";
import { fetchMineProfile } from "../../store/actions/profile/profileActions";
import CreateOffer from "../Cards/CreateOfferCard/CreateOffer";
import { Drawer as HeaderDrawer } from "./Drawer/Drawer";
import useSearch from "../../hooks/useOffers/useSearch";
// import useQueryString from "../../hooks/useOffers/useQueryString";

const Header = () => {
  // const setOpenFilters = useState(false)[1];
  const [showSearchBar, setShowSearchBar] = useState(true);
  const [showCreateOfferModal, setShowCreateOfferModal] = useState(false);
  const { t } = useTranslation();
  const theme = useTheme();
  const searchRef = useRef(null);
  const matches = useMediaQuery(theme.breakpoints.down("md"));
  const user = useSelector(selectUserId);
  const search = useSearch(() => {});
  const dispatch = useDispatch();
  const name = useSelector(selectProfileName);
  const history = useHistory();
  const routeMatch = useRouteMatch();
  const searchMobileRef = useRef(null);
  const [openDrawer, setOpenDrawer] = useState(false);

  useEffect(() => {
    if (user && user?.length > 0) {
      dispatch(fetchMineProfile());
    }
  }, []);
  useEffect(() => {
    setUserPopoverOpen(false);
    setUserAnchorEl(null);
    return () => {
      setUserPopoverOpen(false);
      setUserAnchorEl(null);
    };
  }, []);
  useEffect(() => {
    searchRef.current.value = search.searchString ?? "";
  }, [search.searchString]);
  useEffect(() => {
    if (history.location.pathname !== "/home") {
      setShowSearchBar(false);
    } else {
      setShowSearchBar(true);
    }
  }, [history.location.pathname]);

  // useEffect(() => {
  //   if (queryStringHook.loadedFromURL) {
  //     const queryObject = new URLSearchParams(
  //       convertQueryStringForFrontend(queryStringHook.queryString)
  //     );
  //     if (queryObject.has("search")) {
  //       searchRef.current.value = queryObject.get("search");
  //       searchMobileRef.current.value = queryObject.get("search");
  //     }
  //   }
  // });

  const closeCreateOfferModal = () => {
    setShowCreateOfferModal(false);
  };

  if (showCreateOfferModal) {
    document.body.style.overflow = "hidden";
  } else {
    document.body.style.overflow = "auto";
  }

  const [postsPopoverOpen, setPostsPopoverOpen] = useState(false);
  const [postsAnchorEl, setPostsAnchorEl] = useState(null);

  const [msgPopoverOpen, setMsgPopoverOpen] = useState(false);
  const [msgAnchorEl, setMsgAnchorEl] = useState(null);

  const [userPopoverOpen, setUserPopoverOpen] = useState(false);
  const [userAnchorEl, setUserAnchorEl] = useState(null);

  const [shouldShow, setShouldShow] = useState(true);

  useEffect(() => {
    let shouldShowHeader = true;
    if (
      location.pathname === LOGIN_PAGE ||
      location.pathname === REGISTER_PAGE ||
      location.pathname === REGISTER_SUCCESSFUL_PAGE ||
      location.pathname === FORGOT_PASSWORD_PAGE ||
      location.pathname === FORGOT_PASSWORD_MAIL_SENT ||
      location.pathname === RESET_PASSWORD_PAGE
    ) {
      shouldShowHeader = false;
    }
    setShouldShow(shouldShowHeader);
  }, [location.pathname, user, routeMatch]);

  useEffect(() => {
    setUserPopoverOpen(false);
    setMsgPopoverOpen(false);
    setPostsPopoverOpen(false);
  }, [location.pathname]);
  const handleNavigateLogin = () => {
    setShouldShow(false);
    history.push(LOGIN_PAGE);
  };
  const handleNavigateRegister = () => {
    setShouldShow(false);
    history.push(REGISTER_PAGE);
  };

  let listener;
  const handleFocusSearch = () => {
    listener = (event) => {
      if (event.keyCode === 13) {
        event.preventDefault();
        handleSearch(searchRef.current.value);
      }
    };
    searchRef.current.addEventListener("keyup", listener);
  };
  const handleBlurSearch = () => {
    searchRef.current.removeEventListener("keyup", listener);
  };
  const handleSearch = (value) => {
    if (
      history.location.pathname !== HOME_PAGE &&
      history.location.pathname !== BASE_PAGE
    ) {
      const newQueryString = new URLSearchParams({ search: value });
      history.push({
        pathname: HOME_PAGE,
        search: newQueryString.toString(),
      });
    } else {
      search.searchOffers(value);
    }
  };
  // const toggleFilters = () => {
  //   setOpenFilters((prevState) => !prevState);
  // };

  const handleToggleDrawer = () => {
    setOpenDrawer(!openDrawer);
  };

  const handleLogoClick = () => {
    history.push({
      pathname: HOME_PAGE,
      state: {
        logo: true,
      },
    });
  };

  return (
    <HeaderContainer style={{ display: shouldShow ? "block" : "none" }}>
      <AppBar
        elevation={0}
        position="fixed"
        sx={{ backgroundColor: "white", zIndex: "80" }}
      >
        <Toolbar>
          <ToolsContainer>
            <LogoContainer onClick={() => handleLogoClick()}>
              <LogoHorizontal />
            </LogoContainer>
            {matches && (
              <Drawer
                open={openDrawer}
                toggleOpen={handleToggleDrawer}
                content={
                  <HeaderDrawer
                    toggleDrawer={handleToggleDrawer}
                    addOffer={() => setShowCreateOfferModal(true)}
                  />
                }
              />
            )}
            <SearchInput
              fullWidth
              InputProps={{
                endAdornment: (
                  <EndIcon size="36px">
                    <SearchIcon
                      onClick={() => handleSearch(searchRef.current.value)}
                    />
                  </EndIcon>
                ),
              }}
              placeholder={t("header.searchOffers")}
              onFocus={handleFocusSearch}
              onBlur={handleBlurSearch}
              ref={searchRef}
            />
            {user ? (
              <ToolsButtonsContainer mobile={matches}>
                {matches ? (
                  <ToggleDrawerButton>
                    <IconButton onClick={handleToggleDrawer}>
                      <MenuOutlinedIcon />
                    </IconButton>
                  </ToggleDrawerButton>
                ) : (
                  <React.Fragment>
                    <AddOfferButton
                      type="submit"
                      variant="contained"
                      fullWidth
                      buttoncolor={selectedTheme.primaryYellow}
                      textcolor={selectedTheme.primaryDarkText}
                      onClick={() => {
                        setUserPopoverOpen(false);
                        setUserAnchorEl(null);
                        setShowCreateOfferModal(true);
                      }}
                    >
                      {t("header.addOffer")}
                    </AddOfferButton>
                    <IconButton
                      onClick={(e) => {
                        setPostsPopoverOpen(true);
                        setPostsAnchorEl(e.currentTarget);
                      }}
                      style={{
                        background: selectedTheme.primaryIconBackgroundColor,
                        color: selectedTheme.primaryPurple,
                      }}
                    >
                      <Autorenew />
                    </IconButton>
                    <IconButton
                      onClick={(e) => {
                        setMsgPopoverOpen(true);
                        setMsgAnchorEl(e.currentTarget);
                      }}
                      style={{
                        background: selectedTheme.primaryIconBackgroundColor,
                        color: selectedTheme.primaryPurple,
                      }}
                    >
                      <Badge badgeContent={3} color="primary">
                        <MailIcon />
                      </Badge>
                    </IconButton>
                    <UserButton
                      onClick={(e) => {
                        setUserPopoverOpen(true);
                        setUserAnchorEl(e.currentTarget);
                      }}
                    >
                      <UserName>{name}</UserName>
                      <IconButton
                        style={{
                          background: selectedTheme.primaryIconBackgroundColor,
                          color: selectedTheme.primaryPurple,
                        }}
                      >
                        <AccountCircle />
                      </IconButton>
                    </UserButton>
                  </React.Fragment>
                )}
              </ToolsButtonsContainer>
            ) : (
              <AuthButtonsContainer mobile={matches}>
                {matches ? (
                  <ToggleDrawerButton>
                    <IconButton onClick={handleToggleDrawer}>
                      <MenuOutlinedIcon />
                    </IconButton>
                  </ToggleDrawerButton>
                ) : (
                  <React.Fragment>
                    <LoginButton
                      type="submit"
                      variant="contained"
                      fullWidth
                      buttoncolor={selectedTheme.primaryPurple}
                      textcolor={selectedTheme.offerBackgroundColor}
                      onClick={handleNavigateLogin}
                    >
                      {t("login.headerTitle")}
                    </LoginButton>
                    <RegisterButton
                      type="submit"
                      variant="contained"
                      fullWidth
                      buttoncolor={selectedTheme.primaryYellow}
                      textcolor={selectedTheme.primaryDarkText}
                      onClick={handleNavigateRegister}
                    >
                      {t("register.headerTitle")}
                    </RegisterButton>
                  </React.Fragment>
                )}
              </AuthButtonsContainer>
            )}
          </ToolsContainer>
        </Toolbar>
        {user && (
          <React.Fragment>
            <PopoverComponent
              anchorEl={postsAnchorEl}
              open={postsPopoverOpen}
              onClose={() => {
                setPostsPopoverOpen(false);
                setPostsAnchorEl(null);
              }}
              content={<MyPosts />}
            />
            <PopoverComponent
              anchorEl={msgAnchorEl}
              open={msgPopoverOpen}
              onClose={() => {
                setMsgPopoverOpen(false);
                setMsgAnchorEl(null);
              }}
              content={<MyMessages />}
            />
            <PopoverComponent
              anchorEl={userAnchorEl}
              open={userPopoverOpen}
              onClose={() => {
                setUserPopoverOpen(false);
                setUserAnchorEl(null);
              }}
              content={<MyProfile />}
            />
          </React.Fragment>
        )}
      </AppBar>
      <SearchInputMobile
        fullWidth
        shouldShow={showSearchBar}
        ref={searchMobileRef}
        placeholder={t("header.searchOffers")}
        InputProps={{
          endAdornment: (
            <EndIcon size="36px">
              <SearchIcon
                onClick={() => handleSearch(searchMobileRef.current.value)}
              />
            </EndIcon>
          ),
        }}
        italicPlaceholder
        onFocus={handleFocusSearch}
        onBlur={handleBlurSearch}
      />
      {/* <FilterCard
        responsive={true}
        responsiveOpen={openFilters}
        closeResponsive={toggleFilters}
      /> */}
      {showCreateOfferModal && (
        <CreateOffer closeCreateOfferModal={closeCreateOfferModal} />
      )}
    </HeaderContainer>
  );
};

Header.propTypes = {
  isGrid: PropTypes.bool,
  showModalHandler: PropTypes.func,
};

export default Header;
