import * as React from 'react';
import { useContext, useEffect, useLayoutEffect } from 'react';
import { useQuery } from '@apollo/client';
import { MenuConfig } from '@assets/js-menu/ConfigComponent';
import { ListAdditional } from '@assets/js-menu/ListAdditional';
import { GET_PAGES, GET_SECTIONS, GET_SECTIONS_ROOT } from '@assets/js-menu/query';
import { Loading } from '@assets/js-menu/Loading';
import { List } from '@assets/js-menu/List';
import { getConfigData } from '@assets/js-menu/hooks/getConfig';
import { IMenuSection, IPage } from '@assets/js-menu/GraphQLInterfaces';

export interface IListDataProps {
   contentLoaded?(): void;
}

export function ListData(props: IListDataProps) {
   const context = useContext(MenuConfig);
   const additionalMenu = getConfigData().config?.additionalMenu;

   const { loading: loadingMenu, error: errorMenu, data: dataMenu } = useQuery(GET_SECTIONS, {
      variables: { id: context.menuId },
      skip: !context.menuId,
      context: {getMethod: true}
   });
   const { loading: loadingRoot, error: errorRoot, data: dataRoot } = useQuery(GET_SECTIONS_ROOT, {
      skip: !!context.menuId,
      context: {getMethod: true}
   });
   const { loading: loadingPages, error: errorPages, data: dataPages } = useQuery(GET_PAGES, {
      variables: { label: additionalMenu },
      skip: !additionalMenu,
      context: {getMethod: true}
   });

   const loading = loadingMenu || loadingRoot || loadingPages;
   const error = errorMenu || errorRoot || errorPages;

   useEffect(() => {
      if (props.contentLoaded && !loadingMenu && !loadingRoot && (additionalMenu && !loadingPages)) {
         props.contentLoaded();
      }
   });

   useLayoutEffect(() => {
      context.setLoading(loading);
      context.setRootLoading(loadingRoot);
   },[loading, loadingRoot]);

   if (loading || error) {
      return <Loading/>;
   }
   const sections = ((context.menuId) ? dataMenu.menu[0] : { children: dataRoot.menu }) as IMenuSection;

   return (
      <React.Fragment>
         <List section={sections}/>
         {additionalMenu && !context.menuId && <ListAdditional pages={dataPages.pages as IPage[]}/>}
      </React.Fragment>
   );

}
