import React, { isValidElement, Children, ReactNode } from 'react';
import {
  CollectionPageHeader,
  CollectionPageHeaderElement,
} from '../../components/CollectionPageHeaderNew';
import {
  CollectionPageContent,
  CollectionPageContentElement,
} from '../../components/CollectionPageContent';
import {
  CollectionPageFooter,
  CollectionPageFooterElement,
} from '../../components/CollectionPageFooter';

export function useCollectionPageChild(children: ReactNode) {
  // 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, index) => {
      let newChild = null;
      if (isValidElement(child)) {
        switch (child.type) {
          case CollectionPageHeader:
            const header = child as CollectionPageHeaderElement;
            newChild = header.type.useCollectionPageHeader(header);
            break;
          case CollectionPageContent:
            const content = child as CollectionPageContentElement;
            newChild = content.type.useCollectionPageContent(content);
            break;
          case CollectionPageFooter:
            const footer = child as CollectionPageFooterElement;
            newChild = footer.type.useCollectionPageFooter(footer);
            break;
          default:
            // WIP: Eventually once we will support all child types this will return null
            newChild = child;
        }
      }

      if (newChild === null) {
        return null;
      }
      return React.cloneElement(newChild, { key: index });
    })
    .filter((c) => c);
}
