import * as React from 'react';
import styled from 'styled-components';

import type { JSX } from 'react';

import {
  type SearchFacet,
  type SearchFacetCount,
  type SearchFilterItem,
} from '@redocly/theme/core/types';
import { Tag } from '@redocly/theme/components/Tag/Tag';
import { useThemeHooks } from '@redocly/theme/core/hooks';

type SearchGroupsProps = {
  facets: SearchFacet[];
  searchFilter: SearchFilterItem[];
  groupField: string;
  onFilterChange: (field: string, value: string[], isQuickFilter?: boolean) => void;
  onQuickFilterReset: () => void;
};

export function SearchGroups({
  facets,
  searchFilter,
  groupField,
  onFilterChange,
  onQuickFilterReset,
}: SearchGroupsProps): JSX.Element {
  const groupFacets = facets.filter((facet) => facet.field === groupField);
  const { useTranslate } = useThemeHooks();
  const { translate } = useTranslate();

  const handleGroupTagClick = (
    value: string,
    fieldId: string,
    active: boolean,
    currentValues: string[],
  ) => {
    const values = active
      ? currentValues.filter((item) => item !== value)
      : [...currentValues, value];
    onFilterChange(fieldId, values, true);
  };

  return (
    <SearchGroupsWrapper>
      <GroupTag
        borderless
        active={!searchFilter.some((item) => item.isQuickFilter)}
        onClick={() => searchFilter.some((item) => item.isQuickFilter) && onQuickFilterReset()}
        selectable
      >
        {translate('search.groups.all', 'All')}
      </GroupTag>
      <Divider />
      {groupFacets.flatMap((facet) =>
        facet.values.map((facetCount, index) => {
          const { value, count, isCounterVisible } = facetCount as SearchFacetCount;
          const currentValues =
            searchFilter.find((item) => item.field === facet.field)?.values || [];
          const active = currentValues?.includes(value);
          return (
            <GroupTag
              key={`${facet.field}-${index}`}
              onClick={() => handleGroupTagClick(value, facet.field, active, currentValues)}
              active={active}
              borderless
              selectable
            >
              {value} {isCounterVisible && <span>{count}</span>}
            </GroupTag>
          );
        }),
      )}
    </SearchGroupsWrapper>
  );
}

const SearchGroupsWrapper = styled.div`
  display: flex;
  gap: 4px;
  padding: var(--spacing-md);
`;

const GroupTag = styled(Tag)`
  cursor: pointer;
  gap: 4px;
`;

const Divider = styled.div`
  border-right: 1px solid var(--border-color-secondary);
  margin: 5px 5px 5px 0;
`;
