import React, { memo, useCallback, useMemo } from "react";
import { RecoilRoot } from "recoil";
import { Controller } from "@tingwu/core";
import { TingwuContext } from "../../context";
import { ConnectController } from "./connectController";

export interface ProviderProps {
  controller: Controller;
  enableRecoilRoot?: boolean;
  children?: React.ReactNode | undefined;
}

export const Provider: React.FC<ProviderProps> = memo(props => {
  const { controller, enableRecoilRoot = true, children } = props;

  const getController = useCallback(() => {
    return controller;
  }, [controller]);

  const tingwuContextValue = useMemo(() => {
    return {
      getController,
    };
  }, [getController]);

  const node = (
    <TingwuContext.Provider value={tingwuContextValue}>
      <ConnectController controller={controller} />
      {children}
    </TingwuContext.Provider>
  );

  if (enableRecoilRoot) {
    return <RecoilRoot>{node}</RecoilRoot>;
  }

  return node;
});
