import {
  DropdownLayoutOption,
  DropdownLayoutValueOption,
  MultiSelectCheckbox,
  MultiSelectCheckboxProps,
} from '@wix/design-system';
import React from 'react';
import { observer } from 'mobx-react-lite';
import { KeyedItem } from '@wix/bex-core';
import { DropdownSelectState } from '../../state';
import { FilterProps } from '../../model';
import { useWindowFlipPopoverProps } from '../../utils/useWindowFlipPopoverProps';
import { useDropdownTranslationContext } from '../../providers';

export type KeyedItemOption<T> = DropdownLayoutValueOption & {
  keyedItem: KeyedItem<T>;
};

export type MultiSelectCheckboxFilterBaseOption<V> =
  | KeyedItemOption<V>
  | DropdownLayoutOption;

export interface MultiSelectCheckboxFilterBaseProps<V>
  extends Partial<MultiSelectCheckboxProps>,
    FilterProps<V[]> {
  /**
   * Applies a data-hook HTML attribute that can be used in the tests
   * @default `collection-filter-${filter.name}`
   */
  dataHook?: string;
  options: MultiSelectCheckboxFilterBaseOption<V>[];
  dropdownSelect: DropdownSelectState<V>;
  placeholder?: string;
}

function _MultiSelectCheckboxFilterBase<V>(
  props: MultiSelectCheckboxFilterBaseProps<V>,
) {
  const {
    filter,
    dropdownSelect,
    options,
    placeholder,
    popoverProps,
    ...rest
  } = props;

  const {
    select: { selectedKeys },
  } = dropdownSelect;
  const { translate } = useDropdownTranslationContext();

  const { windowFlipPopoverProps, inputRef } = useWindowFlipPopoverProps({
    popoverProps,
  });

  return (
    <MultiSelectCheckbox
      inputRef={(ref) => {
        inputRef.current = ref;
      }}
      dataHook={`collection-filter-${filter.name}`}
      border="round"
      textOverflow="ellipsis"
      options={options}
      placeholder={placeholder ?? translate('placeholder')}
      selectedOptions={selectedKeys}
      popoverProps={windowFlipPopoverProps}
      {...rest}
    />
  );
}

export const MultiSelectCheckboxFilterBase = observer(
  _MultiSelectCheckboxFilterBase,
);
