import React, { useState } from 'react';
import { observer } from 'mobx-react-lite';
import { CollectionState, FiltersMap } from '@wix/bex-core';
import { TableV2 } from './TableV2';
import { TableState } from '../../state';
import { useWixPatternsContainer } from '@wix/bex-core/react';
import { CollectionTableBaseProps } from '../CollectionTable';
import type { TableSectionsProp } from '../TableSections';

export interface TableCompatProps<T, F extends FiltersMap>
  extends CollectionTableBaseProps<T, F> {
  /**
   * A collection state instance created with [useCollection](./?path=/story/common-hooks--usecollection)
   * @external
   */
  state: CollectionState<T, F> | TableState<T, F>;
  sections?: TableSectionsProp<T>;
}

function _TableCompat<T, F extends FiltersMap = FiltersMap>(
  props: TableCompatProps<T, F>,
) {
  const container = useWixPatternsContainer();

  const [state] = useState(() =>
    props.state instanceof TableState
      ? props.state
      : new TableState<T, F>({
          collection: props.state,
          container,
        }),
  );

  return <TableV2 {...props} state={state} />;
}

export const TableCompat = observer(_TableCompat);
