import {
  DropdownLayoutOption,
  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 { useBmHarmonyTheme } from '../../hooks/useBmHarmonyTheme';
import { useDropdownTranslationContext } from '../../providers';

export type KeyedItemOption<T> = DropdownLayoutOption & {
  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,
  });
  const isBmHarmonyTheme = useBmHarmonyTheme();

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

export const MultiSelectCheckboxFilterBase = observer(
  _MultiSelectCheckboxFilterBase,
);
