import React, { useEffect, useState } from 'react';
import { observer } from 'mobx-react-lite';
import { CollectionState, FiltersMap } from '@wix/bex-core';
import { CollectionTableBaseProps } from '../CollectionTable';
import { runInAction } from 'mobx';
import {
  VirtualTableRepeater,
  VirtualTableRepeaterProps,
} from '../VirtualGridRepeater/VirtualTableRepeater';
import { TableBase } from './TableBase';
import { VirtualGridStateProvider } from '../VirtualGridRepeater/VirtualGridStateContext';
import { TableState } from '../../state';
import { useWixPatternsContainer } from '@wix/bex-core/react';
import { getVirtualTableProps } from './getVirtualTableProps';
import type { TableSectionsProp } from '../TableSections';

export interface TableVirtualProps<T, F extends FiltersMap>
  extends CollectionTableBaseProps<T, F> {
  rowHeight?: number | ((item: T, index: number) => number);
  estimatedRowHeight?: number;
  state: CollectionState<T, F> | TableState<T, F>;
  sections?: TableSectionsProp<T>;
}

function _TableVirtual<T, F extends FiltersMap = FiltersMap>(
  props: TableVirtualProps<T, F>,
) {
  const { rowHeight, estimatedRowHeight, horizontalScroll = true } = props;
  const container = useWixPatternsContainer();

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

  useEffect(() => {
    runInAction(() => {
      state.virtual.rowHeight = rowHeight;
    });
  }, [rowHeight]);

  useEffect(() => {
    if (estimatedRowHeight == null) {
      return;
    }
    runInAction(() => {
      state.virtual.estimatedRowHeight = estimatedRowHeight;
    });
  }, [estimatedRowHeight]);

  const [BodyElementType] = useState(
    () =>
      ({ children }: VirtualTableRepeaterProps) =>
        (
          <VirtualGridStateProvider value={state.virtual}>
            <VirtualTableRepeater>{children}</VirtualTableRepeater>
          </VirtualGridStateProvider>
        ),
  );

  return (
    <TableBase
      {...props}
      {...getVirtualTableProps({ horizontalScroll })}
      state={state}
      horizontalScroll={horizontalScroll}
      isApplyColumnWidthStyle={true}
      BodyElementType={BodyElementType}
    />
  );
}
export const TableVirtual = observer(_TableVirtual);
