import React, { useState, useCallback, useContext, useMemo } from "react";
import { useTranslation } from "react-i18next";
import styled from "styled-components";
import { FilterBarBase, FilterBarWrapper, ItemCount } from "@arcteryx/components-filterbar";
import { Breakpoint } from "@arcteryx/components-typography";
import { adaptSort } from "@arcteryx/data-models";
import { SiteContext } from "@arcteryx/components-contexts";
import { FilterRefinementsApplied } from "./FilterRefinementsApplied";
import { FilterRefineCategory } from "./FilterRefineCategory";
import { FilterSortBy } from "./FilterSortBy";
import connectFilterBar from "../connectors/connectFilterBar";

const FilterBarContainer = styled(props => <FilterBarBase {...props}/>)`
  top: -2px;
  * {
    box-sizing: border-box!important;
  }
  .arc-Filter--Filter {
    div[class*=" filter-dropdown_"], div[class*="filter-title"]  {
      z-index: 100;
      background-color: var(--white);
    }
  }
  .item-count {
    z-index: 100;
    background-color: var(--white);
  }
  .filter-category-title {
    z-index: 100;
    background-color: var(--white);
    ${Breakpoint("xl")`
      border-bottom-width: 0;
    `}
  }
`;

const FilterBarWrapperBase = styled(props => <FilterBarWrapper {...props} />)`
  width: 98%;
  ${Breakpoint("sm")`
    width: 94%;
  `}
  ${Breakpoint("lg")`
    width: 88%;
  `}
`;

const ItemCountBase = styled(props => <ItemCount {...props}/>)``;


export const Overlay = styled.div`
  content: "";
  width: 300%;
  height: 100vh;
  overflow: hidden;
  background-color: rgba(0, 0, 0, 0.5);
  position: fixed;
  top: 0;
  left: 0;
  z-index: 2;
`;

const FilterBarUnconnected = ({
  facets = [
    { name: "gender", data: { mocked: 0 } },
    { name: "collection", data: { mocked: 0 } },
    { name: "categories", data: { mocked: 0 } },
    { name: "materials", data: { mocked: 0 } },
    { name: "colors.BaseColor", data: { mocked: 0 } },
    { name: "review_value_rounded", data: { mocked: 0 } },
  ],
  selectedFacets = {
    gender: "",
    collection: "",
    categories: "",
    materials: "",
    "colors.BaseColor": "",
    review_value_rounded: "",
  },
  itemCount = 0,
  indexName,
}) => {
  const { t } = useTranslation("container-search");
  // Keep these comments - used for i18next-parser
  // t("gender")
  // t("categories")
  // t("collection")
  // t("properties")
  // t("materials")
  // t("colours")
  // t("rating")
  // t("In Stock")
  // t("Refine")
  // t("Items")
  // t("MALE")
  // t("FEMALE")
  // t("NEUTRAL")
  // t("natural")
  // t("Name (A→Z)")
  // t("Name (Z→A)")
  // t("What's New")
  // t("Top Rated")
  // t("Weight (Low→High)")
  // t("Price (Low→High)")
  // t("Price (High→Low)")
  // t("Search Result")

  const [activeCategory, setActiveCategory] = useState(null);
  const [activeFilters, setActiveFilters] = useState(null);
  const handleSetActiveFilters = useCallback((val) => setActiveFilters(val), []);
  const handleSetActiveCategory = useCallback((val) => setActiveCategory(val), []);
  const { market } = useContext(SiteContext);
  const sort = adaptSort(indexName, market);
  // calculate facets only once on mount to avoid re-render and algolia api calls with result facets
  const filteredFacets = useMemo(() => {
    let filteredFacets;
    switch (market) {
      case "outdoor":
        filteredFacets = facets;
        break;
      case "outlet":
        filteredFacets = facets.filter((facet) => facet.name !== "review_value_rounded");
        break;
      case "leaf":
        filteredFacets = facets.filter(
          (facet) =>
            facet.name !== "review_value_rounded" &&
            facet.name !== "materials" &&
            facet.name !== "collection" &&
            facet.name !== "activities"
        );
        break;
      default:
        filteredFacets = facets;
    }
    return filteredFacets;
  }, []);

  const handleOverlayClick = () => {
    setActiveFilters(null);
    setActiveCategory(null);
  };

  return (
    <>
      <FilterBarContainer isActive={activeFilters}>
        <FilterBarWrapperBase className={`${activeFilters || activeCategory ? "active" : ""}`}>
          <ItemCountBase productCount={itemCount} catId={"items"} label={t("Items")} className="item-count" />
          <FilterRefineCategory
            context={"filter"}
            facets={filteredFacets}
            selectedFacets={selectedFacets}
            activeFilters={activeFilters}
            activeCategory={activeCategory}
            handleSetActiveFilters={handleSetActiveFilters}
            handleSetActiveCategory={handleSetActiveCategory}
          />
          {sort && (
            <FilterSortBy
              defaultRefinement={indexName}
              attribute={sort?.id}
              items={sort?.items}
              activeFilters={activeFilters}
              activeCategory={activeCategory}
              handleSetActiveFilters={handleSetActiveFilters}
              handleSetActiveCategory={handleSetActiveCategory}
            />
          )}
        </FilterBarWrapperBase>
      </FilterBarContainer>
      <FilterRefinementsApplied sortList={sort?.items} indexName={indexName} />
      {activeFilters || activeCategory ? <Overlay className="overlay" onClick={handleOverlayClick} /> : ""}
    </>
  );
};

export const FilterBar = connectFilterBar(React.memo(FilterBarUnconnected));
