import React from 'react';
import Table from '../..';
import Loader from '../../../Loader';
import Box from '../../../Box';

export default {
  title: 'Table',
  component: Table,
};

export const InitialItemsNotScrollable = () => {
  const [data, setData] = React.useState(
    [] as { id: string; title: string; subtitle: string }[],
  );

  const [container, setContainer] = React.useState<HTMLElement | undefined>();

  const pageRef = React.useRef(1);
  const [, setTick] = React.useState({});

  const limit = 2;

  const fetchMoreData = (page: number) => {
    pageRef.current = page;
    setTick({});
    setTimeout(() => {
      const items = Array(500)
        .fill(0)
        .map((_, i) => ({
          id: String(i),
          title: `Title ${i}`,
          subtitle: `Subtitle ${i}`,
        }));

      const offset = (page - 1) * limit;
      setData([...data, ...items.slice(offset, offset + limit)]);
    }, 500);
  };

  React.useEffect(() => {
    fetchMoreData(pageRef.current);
  }, []);

  return (
    <div
      ref={el => setContainer(el as HTMLElement | undefined)}
      style={{ maxHeight: '258px', overflow: 'auto' }}
    >
      <Table
        dataHook="table"
        infiniteScroll
        hasMore
        loadMore={() => {
          fetchMoreData(pageRef.current + 1);
        }}
        initialLoad={false}
        itemsPerPage={limit}
        scrollElement={container}
        loader={
          <Box align="center" padding="large">
            <Loader />
          </Box>
        }
        data={[...data]}
        columns={[
          { title: 'Title', render: row => row.title },
          { title: 'Subtitle', render: row => row.subtitle },
        ]}
      >
        <Table.Content />
      </Table>
    </div>
  );
};
