import React, { useMemo } from 'react';
import { useSelector } from 'react-redux';
import { ScreenContext, ComponentContext, PanelContext, FilterContext } from '../../Context';
import { getScreenId, getTopScreenId } from 'utils/screen';

function ScreenEditProvider({ children }) {
  const screensById = useSelector((state: any) => state.screensById);
  const componentsById = useSelector((state: any) => state.componentsById);
  const panelsById = useSelector((state: any) => state.panelsById);
  const filters = useSelector((state: any) => state.filters.list);
  const screens = useSelector((state: any) => state.screens.list) || [];
  const _screens = screens?.filter((d) => !d.deletedAt);

  const screenId = getTopScreenId();
  const stateId = getScreenId();

  const screenContextValue = useMemo(
    () => ({
      screenId,
      stateId,
      screens: _screens,
      screensById
    }),
    [screenId, stateId, screensById, _screens]
  );

  const componentContextValue = useMemo(
    () => ({
      componentsById
    }),
    [componentsById]
  );

  const panelContextValue = useMemo(
    () => ({
      panelsById
    }),
    [panelsById]
  );

  const filterContextValue = useMemo(
    () => ({
      filters
    }),
    [filters]
  );

  return (
    <ScreenContext.Provider value={screenContextValue}>
      <ComponentContext.Provider value={componentContextValue}>
        <PanelContext.Provider value={panelContextValue}>
          <FilterContext.Provider value={filterContextValue}>{children}</FilterContext.Provider>
        </PanelContext.Provider>
      </ComponentContext.Provider>
    </ScreenContext.Provider>
  );
}

export default ScreenEditProvider;
