import { isValidElement, Children, ReactNode, ReactElement } from 'react';
import { ContentProps, Page, HeaderProps } from '@wix/design-system';
import {
  SettingsPageHeader,
  SettingsPageHeaderElement,
} from '../../components/SettingsPageHeader';
import {
  SettingsPageContent,
  SettingsPageContentElement,
} from '../../components/SettingsPageContent';

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

export function useSettingsPageChild(
  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 SettingsPageHeader:
            const header = child as SettingsPageHeaderElement;
            return header.type.useSettingsPageHeader(header);
          case SettingsPageContent:
            const content = child as SettingsPageContentElement;
            return content.type.useSettingsPageContent(content, scrollableRef);
          default:
            // TODO: Check whenever we should filter out or not other Page components
            return null;
        }
      }

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