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

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

import { Button } from '@redocly/theme/components/Button/Button';
import { ResetIcon } from '@redocly/theme/icons/ResetIcon/ResetIcon';
import { useThemeHooks } from '@redocly/theme/core/hooks';
import { SearchFilterFieldSelect } from '@redocly/theme/components/Search/FilterFields/SearchFilterFieldSelect';
import { SearchFilterFieldTags } from '@redocly/theme/components/Search/FilterFields/SearchFilterFieldTags';

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

export function SearchFilterField({
  className,
  facet,
  filter,
  query,
  quickFilterFields,
  onFilterChange,
  onFacetReset,
}: SearchFilterFieldProps): JSX.Element {
  const { useTranslate } = useThemeHooks();
  const { translate } = useTranslate();
  const selectedValues = filter.find((item) => item.field === facet.field)?.values || [];

  const onChange = (value: string | string[]) => {
    onFilterChange(facet.field, value, facet.field in quickFilterFields);
  };

  const onReset = () => {
    onFacetReset(facet.field);
  };

  return (
    <FilterFieldWrapper data-component-name="Search/SearchFilterField" className={className}>
      <FilterFieldLabel>
        {facet.name}
        {selectedValues.length > 0 && (
          <Button
            data-translation-key="search.filter.field.reset"
            icon={<ResetIcon />}
            variant="ghost"
            size="small"
            onClick={onReset}
          >
            {translate('search.filter.field.reset', 'Reset')}
          </Button>
        )}
      </FilterFieldLabel>
      {['select', 'multi-select'].includes(facet.type) && (
        <SearchFilterFieldSelect
          facet={facet}
          filter={filter}
          query={query}
          selectedValues={selectedValues}
          onChange={onChange}
        />
      )}
      {/* Special default HTTP Methods filed */}
      {facet.type === 'tags' && (
        <SearchFilterFieldTags facet={facet} selectedValues={selectedValues} onChange={onChange} />
      )}
    </FilterFieldWrapper>
  );
}

const FilterFieldWrapper = styled.div`
  display: flex;
  flex-direction: column;
  gap: 4px;
`;

const FilterFieldLabel = styled.div`
  display: flex;
  justify-content: space-between;
  align-items: center;
`;
