import React, { useCallback, useMemo } from "react";
import { connectRefinementList } from "react-instantsearch-dom";
import styled from "styled-components";
import { ScreenSize } from "@arcteryx/components-typography";
import { FilterTitle, FilterDropdown } from "@arcteryx/components-filterbar";
import { useTranslation } from "react-i18next";
import { facetCategoryMap } from "../helpers";

const RefinementListBase = styled.li`
  padding: 0;
`;

const FitlerTitleBase = styled(props => <FilterTitle {...props}/>)`
  white-space: nowrap;
  @media screen and (max-width: ${ScreenSize.xl}px) {
    display: flex;
    justify-content: center;
    padding: 0 0.866rem 0 1rem !important;
    span {
      justify-content: space-between;
      padding: 0.766rem 0px !important;
      width: 100% !important;
      &:after {
        content: "+";
        line-height: 1;
        float: right;
        position: initial;
        transform-origin: center;
        top: 50%;
        font-family: var(--font-urw);
        transform: rotate(0deg);
      }
    }

    &:before {
      display: none;
    }

    &.active {
      span {
        &:after {
          transform: rotate(-45deg) !important;
        }
      }
    }
  }
`;

const FilterDropdownBase = styled(props => <FilterDropdown {...props}/>)`
  @media screen and (min-width: calc(${ScreenSize.xl}px + 1px)) and (max-width: 1300px) {
    ul {
      width: 550px;
    }
  }
  @media screen and (max-width: ${ScreenSize.xl}px) {
    position: relative;
    top: -1px;
    left: 0;
    ul {
      margin: 0 !important;
    }
  }
  &:before, &:after {
    top: 0 !important;
    height: 100% !important;
  }
  ul {
    margin-bottom: 0 !important;
    padding-bottom: 1.333rem !important;
    label {
      white-space: nowrap;
    }
  }
  &.active {
    ul {
      position: relative;
      z-index: 30;
    }
  }
`;

/* 
* Algolia function connectRefinementList() will return the props:
* - attribute (DOM annotation)
* - items (all available facets of an attribute)
* - refine (function to update the search on user selection)
*/
const RefinementList = ({
  attribute,
  items,
  refine,
  context,
  isActive,
  handleSetActiveCategory,
  handleSetActiveFilters
}) => {
  const { t } = useTranslation("container-search");
  const activeFacets = items
  ?.filter(item => item.isRefined)
  ?.map(item => ({ ...item, catId: attribute, id: item.label?.toLowerCase() }));

  const toggleFilters = () => {
    handleSetActiveFilters(isActive ? null : attribute);
    handleSetActiveCategory(isActive ? null : attribute);
  };
 
  const refineFilter = useCallback((val) => {
    const currentItem = items?.find(item => item?.label.toLowerCase() === val?.id.toLowerCase());
    const value = currentItem?.value;
    refine(value);
    handleSetActiveFilters(null);
    handleSetActiveCategory(null);
  }, [items]);

  const dropdownItems = useMemo(() => {
    const itemsWithId = items?.map((item) => ({ ...item, id: item.label?.toLowerCase() }));
    if(attribute?.toLowerCase() === "review_value_rounded") {
      return itemsWithId.sort((a, b) => b.label - a.label);
    }
    return itemsWithId;
  }, [items, attribute])
  
  if (items?.length) {
    return (
      <>
        <RefinementListBase className={`arc-Filter arc-Filter--Filter ${isActive ? "activeFilter" : ""}`}>
          <FitlerTitleBase
            className="filter-title"
            catId={attribute}
            label={t(facetCategoryMap[attribute])}
            isActive={isActive}
            activeFacets={activeFacets}
            handleCategoryChange={toggleFilters}
          />
          <FilterDropdownBase
            context={context}
            catId={attribute}
            items={dropdownItems}
            hasChildren={false}
            isActive={isActive}
            activeFacets={activeFacets}
            handleFacetClick={refineFilter}
            urlParam={attribute}
          />
        </RefinementListBase>
      </>
    );
  }
  return null;
};

export const FilterRefinementList = connectRefinementList(React.memo(RefinementList));
