import * as React from 'react';
import { useContext, useState } from 'react';
import { FirstLevelNav } from './FirstLevelNav';
import { useQuery } from '@apollo/client';
import { MenuConfig } from '@assets/js-menu/ConfigComponent';
import { Loading } from '@assets/js-menu/Loading';
import { ListData } from '@assets/js-menu/ListData';
import { ExtraList } from './ExtraList';
import { List } from '@assets/js-menu/List';
import { GET_SECTIONS_USER_CURRENCY_ELNINO } from '@assets/js-menu/query';
import { UserBar } from '@assets/js-menu/UserBar';
import { IListRootProps } from '@assets/js-menu/ListRoot';

export function ListRoot(props: IListRootProps) {
   const context = useContext(MenuConfig);
   const [rootMenuId, updateRootMenuId] = useState<Number | null>(null);
   const { loading, error, data } = useQuery(GET_SECTIONS_USER_CURRENCY_ELNINO, {
      variables: { id: context.config.data?.config?.activeSection || null }
   });

   if (loading || error) {
      return <Loading/>;
   } else if (rootMenuId === null) {
      updateRootMenuId(data.menu[0].parents[0]?.id);
      return <Loading/>;
   }

   const updateRootMenuIdCallback = (id: Number) => {
      context.updateMenuId(id);
      updateRootMenuId(id);
   };

   return (
      <div>
         <div className="jsmenu-overlay" onClick={props.closeMenu}></div>
         <div className="sections-responsive">
            <UserBar user={data.user} currencies={data.currency} languages={data.contexts.languages} closeMenu={props.closeMenu}/>
            <FirstLevelNav updateMenu={updateRootMenuIdCallback} items={data.menuRoot} activeId={rootMenuId}/>
            {context.menuId
               ? <ListData/>
               : <List section={{ ...data.menu[0], parent: null }}/>
            }
            {(!context.menuId || context.menuId === rootMenuId) && <ExtraList/>}
         </div>
      </div>
   );
}
