import {
  Dropdown,
  DropdownLayoutValueOption,
  DropdownPropsControlled,
} from '@wix/design-system';
import React from 'react';
import { observer } from 'mobx-react-lite';
import { Filter, KeyedItem } from '@wix/bex-core';
import { DropdownSelectState } from '../../state';
import { BuildSectionOptionsArgs, ListItem } from '../../hooks';
import { FilterProps } from '../../model';
import { useWindowFlipPopoverProps } from '../../utils/useWindowFlipPopoverProps';

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

export interface SingleSelectFilterBaseProps<V>
  extends Omit<Partial<DropdownPropsControlled>, 'onClear'>,
    FilterProps<V[]> {
  filter: Filter<V[]>;
  renderItem?: (item: V, index: number) => ListItem;
  renderSection?: BuildSectionOptionsArgs['renderSection'];
  dropdownSelect: DropdownSelectState<V>;
  placeholder?: string;
}

function _SingleSelectFilterBase<V>(props: SingleSelectFilterBaseProps<V>) {
  const {
    filter,
    dropdownSelect,
    placeholder,
    onSelect,
    renderItem,
    renderSection,
    clearButton,
    disabled,
    options = [],
    popoverProps,
    ...rest
  } = props;

  const {
    select: { selectedValues },
    container: { translate: t },
  } = dropdownSelect;

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

  return (
    <Dropdown
      inputRef={(ref) => {
        inputRef.current = ref;
      }}
      dataHook={`collection-filter-${filter.name}`}
      border="round"
      closeOnSelect
      options={options}
      clearButton={clearButton}
      onClear={clearButton ? dropdownSelect.clear : undefined}
      onClose={() => {
        dropdownSelect.close();
      }}
      selectedId={selectedValues[0]?.key}
      valueParser={(option) => option.label}
      textOverflow="ellipsis"
      placeholder={placeholder ?? t('cairo.selectPlaceholder')}
      onSelect={(option) => {
        const keyedItem = (option as KeyedItemOption<V>)?.keyedItem;
        if (keyedItem) {
          dropdownSelect.setSingle(keyedItem);
        }
        onSelect?.(option, false);
      }}
      popoverProps={windowFlipPopoverProps}
      {...rest}
    />
  );
}

export const SingleSelectFilterBase = observer(_SingleSelectFilterBase);
