import { Page, PageProps } from '@wix/design-system';
import React, { Children, ReactNode } from 'react';
import { CollectionPageContextProvider } from '../../providers';
import { usePageHeader } from '../../hooks/usePageHeader';
import { CollectionPageState } from '@wix/bex-core';
import { useCollectionPageState } from '@wix/bex-core/react';
import { PageWrapperBase } from './PageWrapperBase';

interface PagePropsWithChildren extends PageProps {
  state?: CollectionPageState;
}

export interface InfiniteScrollPageProps extends PagePropsWithChildren {
  children: ReactNode;
}

export function InfiniteScrollPage({
  children,
  ...props
}: InfiniteScrollPageProps) {
  // WSR <Page /> expects a flattened children array
  const childrenArr = Children.toArray(children);

  const { title: pageTitle, header } = usePageHeader(childrenArr);
  const collectionPageState = useCollectionPageState(
    { pageTitle, hasHeader: header != null },
    props.state,
  );

  const { pageState } = collectionPageState;

  return (
    <CollectionPageContextProvider value={collectionPageState}>
      <PageWrapperBase pageState={pageState}>
        <Page {...props}>{childrenArr}</Page>
      </PageWrapperBase>
    </CollectionPageContextProvider>
  );
}
