import React, { useEffect, useRef } from 'react';
import { observer } from 'mobx-react-lite';
import { Dropdown } from '@wix/design-system';
import { FiltersMap } from '@wix/bex-core';
import { MultiLevelSortingState, SortableColumn } from '../../state';

export interface MultiLevelSortingColumnSelectProps<T, F extends FiltersMap> {
  sortableColumn: SortableColumn;
  state: MultiLevelSortingState<T, F>;
  index: number;
}

export function _MultiLevelSortingColumnSelect<T, F extends FiltersMap>(
  props: MultiLevelSortingColumnSelectProps<T, F>,
) {
  const { sortableColumn, state, index } = props;
  const ref = useRef<HTMLInputElement | null>();

  const options = state.getAvailableOptions(sortableColumn.columnId);

  useEffect(() => {
    const id = window.requestAnimationFrame(() => {
      if (!ref.current) {
        return;
      }

      // focus the last added column
      if (sortableColumn.columnId === state.lastManuallyAddedColumnId) {
        state.lastManuallyAddedColumnId = null;
        ref.current.focus();
      }
    });

    return () => {
      window.cancelAnimationFrame(id);
    };
  }, []);

  return (
    <Dropdown
      inputRef={(node) => {
        if (ref) {
          ref.current = node;
        }
      }}
      dataHook={`multi-level-sorting-select-column-${index}`}
      onSelect={({ id }) => {
        state.replaceSort(sortableColumn.columnId, id as string);
      }}
      popoverProps={{
        appendTo: 'window',
      }}
      options={options}
      selectedId={sortableColumn.columnId}
      size="small"
    />
  );
}

export const MultiLevelSortingColumnSelect = observer(
  _MultiLevelSortingColumnSelect,
);
