import Filter from './filter';
import {FC, useEffect} from 'react';
import {context, pIdContext, pageContext, useContextReducer, usePIdContextState} from './context';
import TableList from './table';
import {ChildrenFC} from '@utils';
import {PageProvider} from '@components';

type Props = {
  id: string,
  onClose: () => void,
};

const MenuProvider: ChildrenFC<Pick<Props, 'onClose'>> = function({children, onClose}) {
  const state = useContextReducer(onClose);

  const {Provider} = context;

  return <Provider value={state}>{children}</Provider>;
};

const PIdProvider: ChildrenFC<Pick<Props, 'id'>> = function({children, id}) {
  const state = usePIdContextState(id);
  const {Provider} = pIdContext;

  const dispatch = state[1];
  useEffect(function() {
    dispatch(id);
  }, [dispatch, id]);

  return <Provider value={state}>{children}</Provider>;
};

const ChildMenu: FC<Props> = function({id, onClose}) {
  return (
    <PIdProvider id={id}>
      <MenuProvider onClose={onClose}>
        <PageProvider context={pageContext}>
          <section className='content-main' data-testid='child_menu'>
            <Filter />
            <TableList />
          </section>
        </PageProvider>
      </MenuProvider>
    </PIdProvider>
  );
};

export default ChildMenu;
