import React, { ReactElement, useContext } from 'react';

import { StyledGroupedFilterContent } from './StyledFilters';
import FiltersContext, {
  useChangeGroupFilter,
  useGroupDirtyCheck,
} from './FiltersContext';
import FilterDropdown from './FilterDropdown';
import { getDefaultValue } from './utils';
import { FilterValues } from './types';
import { FilterProps } from './Filter';

const GroupedFilter = <T extends FilterValues, K extends keyof T>({
  label,
  filters,
}: {
  filters: ReactElement<FilterProps<T, K>>[];
  label: string;
}) => {
  const keys = filters.map(filter => filter.props.filterKey);
  const dirty = useGroupDirtyCheck<T, K>(keys);

  const clearableFilters = filters.filter(
    filter => filter.props.clearable !== false
  );
  const clearableKeys = clearableFilters.map(filter => filter.props.filterKey);
  const [changeAndSaveGroup] = useChangeGroupFilter<T, K>(clearableKeys);
  const { values } = useContext(FiltersContext);

  const resetValues = () => {
    const defaultValues = clearableFilters.map(filter => {
      const { filterKey, defaultValue } = filter.props;
      return (
        defaultValue ?? (getDefaultValue((values as T)[filterKey]) as T[K])
      );
    });
    changeAndSaveGroup(defaultValues);
  };
  const onGroupedClearButtonClick =
    clearableKeys.length > 0 ? resetValues : undefined;

  return (
    <FilterDropdown
      dirty={dirty}
      content={
        <StyledGroupedFilterContent>{filters}</StyledGroupedFilterContent>
      }
      buttonText={label}
      onClearButtonClick={onGroupedClearButtonClick}
      data-test-id="grouped-filter-dropdown"
    />
  );
};

export default GroupedFilter;
