import React from 'react';
import { CollectionState, FiltersMap } from '@wix/bex-core';
import { TableVirtual } from './TableVirtual';
import { useWixPatternsContainer } from '@wix/bex-core/react';
import { CollectionTableBaseProps } from '../CollectionTable';
import { TableState } from '../../state';
import { TableCompat } from './TableCompat';
import type { TableSectionsProp } from '../TableSections';

export interface TableProps<T, F extends FiltersMap>
  extends CollectionTableBaseProps<T, F> {
  rowHeight?: number | ((item: T, index: number) => number);
  estimatedRowHeight?: number;
  /**
   * A state instance created using the [`useTableCollection()`](./?path=/story/base-components-collections-table-usetablecollection--usetablecollection) hook, responsible for managing the data displayed in the table.
   * @overrideType [TableState](./?path=/story/base-components-collections-table-tablestate--tablestate)
   * @external
   */
  state: CollectionState<T, F> | TableState<T, F>;

  // a flag to opt out from virtualization
  isVirtual?: boolean;

  /**
   * Configuration for rendering table sections. When provided, the table will render with section headers
   * that group related rows together
   * @external
   */
  sections?: TableSectionsProp<T>;
}

export function Table<T, F extends FiltersMap = FiltersMap>(
  props: TableProps<T, F>,
) {
  const { rowHeight, estimatedRowHeight, isVirtual, ...tableProps } = props;
  const container = useWixPatternsContainer();

  const { internalExperiments } = container;

  const isVirtualExperiment = internalExperiments?.enabled(
    'specs.Cairo.TableVirtualizationAsDefault',
  );
  return isVirtualExperiment && isVirtual !== false && !props.rowDetails ? (
    <TableVirtual
      {...tableProps}
      rowHeight={rowHeight}
      estimatedRowHeight={estimatedRowHeight}
    />
  ) : (
    <TableCompat {...tableProps} />
  );
}
