import { isValidElement, Children, ReactNode, ReactElement } from 'react';
import { ContentProps, Page, HeaderProps } from '@wix/design-system';
import {
  EntityPageHeader,
  EntityPageHeaderElement,
} from '../../components/EntityPageHeader';
import {
  EntityPageContent,
  EntityPageContentElement,
} from '../../components/EntityPageContent';

export interface EntityPageChild {
  Header?: ReactElement<HeaderProps, typeof Page.Header>;
  Content?: ReactElement<ContentProps, typeof Page.Content>;
}

export function useEntityPageChild(
  children: ReactNode,
  scrollableRef: HTMLElement | null,
) {
  // Mapping to raw WDS components since original Page filtering none expected components: https://github.com/wix-private/wix-design-systems/blob/master/packages/wix-style-react/src/Page/Page.js#L626
  return Children.toArray(children)
    .map((child) => {
      if (isValidElement(child)) {
        switch (child.type) {
          case EntityPageHeader:
            const header = child as EntityPageHeaderElement;
            return header.type.useEntityPageHeader(header);
          case EntityPageContent:
            const content = child as EntityPageContentElement;
            return content.type.useEntityPageContent(content, scrollableRef);
          default:
            // TODO: Check whenever we should filter out or not other Page components
            return null;
        }
      }

      return null;
    })
    .filter((c) => c);
}
