import React, { PropsWithChildren } from 'react';
import { observer } from 'mobx-react-lite';
import { FilterProps } from '../../model';
import { BoxProps, CheckboxProps } from '@wix/design-system';
import { MultiInlineCheckboxFilter } from '../MultiInlineCheckboxFilter';
import { MultiSelectCheckboxFilter } from '../MultiSelectCheckboxFilter';
import { useFilterRenderingContext } from '../FilterRenderingContext';
import { useStaticListFilterCollection } from '../../hooks/useStaticListFilterCollection';

const MAX_INLINE_ITEMS = 10;

export interface MultiAutoInlineCheckboxFilterProps<V>
  extends FilterProps<V[]>,
    Partial<Omit<BoxProps, 'filter'>> {
  /**
   * List of items to select from
   * @external
   */
  data: V[];
  /**
   * A function that returns checkbox props for rendering each item checkbox
   * @external
   */
  renderItem?: (
    item: V,
    index: number,
  ) => Partial<PropsWithChildren<CheckboxProps>>;

  /**
   * Maximum of inline items to display
   * @default 10
   * @external
   */
  maxInlineItems?: number;
}

function _MultiAutoInlineCheckboxFilter<V>(
  props: MultiAutoInlineCheckboxFilterProps<V>,
) {
  const { maxInlineItems = MAX_INLINE_ITEMS, data, filter, ...rest } = props;

  const { location } = useFilterRenderingContext();

  const shouldBeRenderedAsDropdown =
    location === 'toolbar' || data.length > maxInlineItems;

  const collection = useStaticListFilterCollection(filter, data);

  return shouldBeRenderedAsDropdown ? (
    <MultiSelectCheckboxFilter
      {...(rest as {})}
      collection={collection}
      filter={filter}
    />
  ) : (
    <MultiInlineCheckboxFilter {...rest} filter={filter} data={data} />
  );
}

export const MultiAutoInlineCheckboxFilter = observer(
  _MultiAutoInlineCheckboxFilter,
);
