import { Page, PageProps } from '@wix/design-system';
import React, { Children, ReactNode } from 'react';
import { CollectionState, FiltersMap } from '@wix/bex-core';
import { CollectionPageHeader } from '../CollectionPageHeader';
import { InfiniteScrollPage } from '../PageWrapper/InfiniteScrollPage';
import { CollectionProvider } from '../CollectionContext';
import { useCollectionPageState } from '@wix/bex-core/react';
import { usePageHeader } from '../../hooks/usePageHeader';

export interface CollectionPageProps<T, F extends FiltersMap>
  extends PageProps {
  /**
   * A collection state instance created with [useCollection](./?path=/story/common-hooks--usecollection)
   * @external
   */
  state: CollectionState<T, F>;
  children?: ReactNode;
  /**
   * Hide total items count
   * @external
   */
  hideTotal?: boolean;
}
/**
 * @deprecated Use [CollectionPage](./?path=%2Fstory%2Fbase-components-pages-collection-page--collectionpage) from
 * `@wix/patterns/page`
 */
export function CollectionPage<T, F extends FiltersMap = FiltersMap>({
  children,
  state,
  hideTotal,
  ...rest
}: CollectionPageProps<T, F>) {
  const childrenArr = Children.toArray(children);

  const { header, title: pageTitle } = usePageHeader(childrenArr);
  const collectionPageState = useCollectionPageState({ pageTitle });

  return (
    <CollectionProvider value={state}>
      <InfiniteScrollPage state={collectionPageState} {...rest}>
        {header && (
          <Page.Header
            {...header.props}
            title={
              hideTotal ? (
                header.props.title
              ) : (
                <CollectionPageHeader state={state}>
                  {header.props.title}
                </CollectionPageHeader>
              )
            }
          />
        )}
        {childrenArr.filter((e) => e !== header)}
      </InfiniteScrollPage>
    </CollectionProvider>
  );
}
