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

import type { JSX } from 'react';
import type { ResolvedFilter } from '@redocly/theme/core/types';

import { breakpoints } from '@redocly/theme/core/utils';
import { useThemeHooks } from '@redocly/theme/core/hooks';
import { Button } from '@redocly/theme/components/Button/Button';
import { FilterIcon } from '@redocly/theme/icons/FilterIcon/FilterIcon';
import { CounterTag } from '@redocly/theme/components/Tags/CounterTag';

export type CatalogClassicActionsProps = {
  onOpenFilter: () => void;
  filters: ResolvedFilter[];
  filterTerm: string;
};

export function CatalogClassicActions(props: CatalogClassicActionsProps): JSX.Element {
  const { onOpenFilter, filterTerm, filters } = props;

  let activeFilters = filterTerm.trim().length > 0 ? 1 : 0;

  for (const filter of filters) {
    if (filter.selectedOptions instanceof Set) {
      activeFilters += filter.selectedOptions.size ? 1 : 0;
    } else if (filter.selectedOptions.from && filter.selectedOptions.to) {
      activeFilters++;
    }
  }

  const { useTranslate, useTelemetry } = useThemeHooks();
  const { translate } = useTranslate();
  const telemetry = useTelemetry();

  return (
    <CatalogActionsWrapper data-component-name="CatalogClassic/CatalogClassicActions">
      <Button
        variant="ghost"
        size="small"
        icon={<FilterIcon />}
        iconPosition="left"
        onClick={() => {
          onOpenFilter();
          telemetry.sendCatalogActionsButtonClickedMessage();
        }}
        data-translation-key="catalog.filters.title"
      >
        {translate('catalog.filters.title', 'Filters')}
      </Button>
      {activeFilters > 0 ? <CounterTag borderless>{activeFilters}</CounterTag> : null}
    </CatalogActionsWrapper>
  );
}

const CatalogActionsWrapper = styled.div`
  display: flex;
  align-items: center;
  gap: var(--catalog-classic-actions-gap);
  padding: var(--catalog-classic-actions-padding-vertical)
    var(--catalog-classic-actions-padding-horizontal);
  min-height: var(--catalog-classic-actions-min-height);
  background-color: var(--catalog-classic-actions-bg-color);

  @media screen and (min-width: ${breakpoints.medium}) {
    display: none;
  }
`;
