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

import type { JSX } from 'react';
import type { SearchFilterItem, SearchFacet } from '@redocly/theme/core/types';

import { Button } from '@redocly/theme/components/Button/Button';
import { CleanIcon } from '@redocly/theme/icons/CleanIcon/CleanIcon';
import { SearchFilterField } from '@redocly/theme/components/Search/SearchFilterField';
import { useThemeHooks } from '@redocly/theme/core/hooks';

export type SearchFilterProps = {
  className?: string;
  facets: SearchFacet[];
  filter: SearchFilterItem[];
  query: string;
  quickFilterFields: string[];
  onFilterChange: (field: string, value: string | string[], isQuickFilter?: boolean) => void;
  onFilterReset: () => void;
  onFacetReset: (field: string) => void;
};

export function SearchFilter({
  className,
  facets,
  filter,
  query,
  quickFilterFields,
  onFilterChange,
  onFilterReset,
  onFacetReset,
}: SearchFilterProps): JSX.Element {
  const { useTranslate } = useThemeHooks();
  const { translate } = useTranslate();
  return (
    <SearchFilterWrapper data-component-name="Search/SearchFilter" className={className}>
      <SearchFilterHeader>
        <span data-translation-key="search.filter.title">
          {translate('search.filter.title', 'Advanced filter')}
        </span>
        <Button
          data-translation-key="search.filter.reset"
          onClick={onFilterReset}
          variant="ghost"
          icon={<CleanIcon />}
        >
          {translate('search.filter.reset', 'Reset filters')}
        </Button>
      </SearchFilterHeader>

      <SearchFilterFields>
        {facets.map((facet, index) => (
          <SearchFilterField
            key={`${facet.field}-${index}`}
            facet={facet}
            filter={filter}
            query={query}
            quickFilterFields={quickFilterFields}
            onFilterChange={onFilterChange}
            onFacetReset={onFacetReset}
          />
        ))}
      </SearchFilterFields>
    </SearchFilterWrapper>
  );
}

const SearchFilterWrapper = styled.div`
  width: 100%;
  max-width: var(--search-filter-width);
  display: flex;
  flex-direction: column;
  padding: var(--search-filter-padding);
  font-size: var(--search-filter-font-size);
  font-weight: var(--search-filter-font-weight);
  line-height: var(--search-filter-line-height);
`;

const SearchFilterHeader = styled.div`
  position: sticky;
  top: 0px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: var(--search-filter-header-padding);
  color: var(--search-filter-header-text-color);
  background-color: var(--search-filter-bg-color);
  z-index: var(--search-filter-header-z-index);
`;

const SearchFilterFields = styled.div`
  display: flex;
  flex-direction: column;
  gap: var(--search-filter-fields-gap);
`;
