import React, { useContext, useEffect, useRef } from "react";
import ReactDOM from "react-dom";
import styled from "styled-components";
import { withRouter } from "react-router-dom";
import { Breakpoint } from "@arcteryx/components-typography";
import { SearchResults } from "./SearchResults";
import { SearchNoResults } from "./SearchNoResults";
import { FilterBar } from "./FilterBar";
import { SearchBox } from "./SearchBox";
import connectSearchBar from "../connectors/connectSearchBar";
import { IndexContext } from "../context/IndexContext";
import { SearchStaticLinks } from "./SearchStaticLinks";

const SearchBarContainer = styled.div``;

const SearchBarWrapper = styled.div`
  padding: 2rem 0.5rem 1rem;
  position: relative;
  z-index: 201;
  background-color: var(--white);
  ${Breakpoint("md")`
    padding: 2rem 0 1rem;
  `}
`;

const SearchBarInner = styled.div`
  max-width: 95.333rem;
  display: flex;
  flex-wrap: nowrap;
  align-items: center;
  justify-content: center;
  margin: 0 auto;
  width: 98%;
  ${Breakpoint("sm")`
    width: 94%;
  `}
  ${Breakpoint("lg")`
    width: 88%;
  `}
`;

const SearchClose = styled.button`
  flex: 0 0 auto;
  font-size: 1.5rem;
  padding-left: 1rem;
  cursor: pointer;
  background: transparent;
  border-width: 0;
  color: var(--black);
`;

const SearchPanel = styled.div`
  max-width: 95.333rem;
  margin: auto;
  width: 98%;
  ${Breakpoint("sm")`
    width: 94%;
  `}
  ${Breakpoint("lg")`
    width: 88%;
  `}
  .aa-Panel {
    position: relative;
    top: auto !important;
    left: auto !important;
    right: auto !important;
    border: none;
    box-shadow: none;
    margin: 0;
    * {
      font-family: var(--font-helvetica);
    }
    .aa-GradientBottom {
      display: none;
    }
  }
  .aa-List {
    .aa-Item {
      padding-left: 9px;
      &[aria-selected="true"] {
        background-color: transparent;
      }
    }
  }
  .aa-ItemActions {
    display: none;
  }
  .aa-ItemLink {
    text-decoration: none;
  }
`;

const SearchPanelContainer = styled.div`
  height: 100vh;
  width: 100%;
`;

const CloseButton = ({ mountNode, location, history }) => {
  const onClose = () => {
    ReactDOM.unmountComponentAtNode(mountNode);
    location.search = "";
    history.push(location);
    document.dispatchEvent(new CustomEvent("search-closed"));
  };

  return (
    <SearchClose data-testid="arc-SearchClose" onClick={onClose}>
      ✕
    </SearchClose>
  );
};

const SearchBar = withRouter(
  ({ mountNode, location, history, searchResults, cmsUrl, query, searchState, store, cmsStaticSearchLinks }) => {
    const { results, isSearchStalled } = searchResults;
    const hasResults = results && results.nbHits !== 0;
    const { analyticsEvents, suggestedSearchContext } = useContext(IndexContext);
    const searchPanelRef = useRef(null);

    useEffect(() => {
      // Check if search is stalled and the user has made a query
      if (!isSearchStalled && query) {
        // If no results then resetSearch = true
        analyticsEvents.handleListingViewedEvent(results, !hasResults);
      }
    }, [searchState, isSearchStalled, hasResults, query, analyticsEvents, results]);

    const renderResults = () => {
      if (!query || (!hasResults && suggestedSearchContext?.redirectUrlPlugin?.data?.length)) {
        return <SearchStaticLinks cmsUrl={cmsUrl} cmsStaticSearchLinks={cmsStaticSearchLinks} />;
      }
      if (hasResults) {
        return (
          <>
            <SearchResults query={query} />
            <FilterBar />
          </>
        );
      }
      return (
        <>
          {store.getState().searching && <SearchPanelContainer />}
          <SearchNoResults query={query} cmsUrl={cmsUrl} />
        </>
      );
    };

    return (
      <SearchBarContainer>
        <SearchBarWrapper>
          <SearchBarInner>
            <SearchBox autoFocus delay={200} searchPanelRef={searchPanelRef} />
            <CloseButton mountNode={mountNode} location={location} history={history} />
          </SearchBarInner>
          <SearchPanel ref={searchPanelRef} />
        </SearchBarWrapper>
        {renderResults()}
      </SearchBarContainer>
    );
  }
);

const ConnectedSearchBar = connectSearchBar(
  // prevent re-render when loading search results
  React.memo(SearchBar, (_, nextProps) => nextProps.searchResults.searching === true)
);

export { SearchBar, ConnectedSearchBar };
