import { useEffect, useLayoutEffect, useState } from "react";

import { getCharacterSlots } from "~/helpers/characterServiceApi";
import { useDispatch } from "~/hooks/useDispatch";
import { BuilderProvider } from "~/subApps/builder/contexts/Builder";
import { PremadeListing } from "~/subApps/builder/routes/PremadeListing";
import { appEnvActions } from "~/tools/js/Shared/actions/appEnv";

import ErrorBoundary from "../../../Shared/components/ErrorBoundary";
import CharacterBuilder from "../CharacterBuilder";

interface CharacterBuilderContainerProps {
  isPremadeListing?: boolean;
}

export function CharacterBuilderContainer(
  props: CharacterBuilderContainerProps
) {
  const dispatch = useDispatch();
  const [isSlotLimitsLoaded, setIsSlotLimitsLoaded] = useState(false);

  useEffect(() => {
    if (!isSlotLimitsLoaded) {
      getCharacterSlots().then((characterSlots) => {
        dispatch(
          appEnvActions.dataSet({
            characterSlots,
          })
        );
        setIsSlotLimitsLoaded(true);
      });
    }
  }, [isSlotLimitsLoaded]);

  useLayoutEffect(() => {
    document
      .getElementsByTagName("body")[0]
      .classList.add(
        "site",
        "body-rpgcharacterbuilder",
        "site-dndbeyond",
        "body-rpgcharacter"
      );
    return () => {
      document
        .getElementsByTagName("body")[0]
        .classList.remove(
          "site",
          "body-rpgcharacterbuilder",
          "site-dndbeyond",
          "body-rpgcharacter"
        );
    };
  }, []);

  return (
    <BuilderProvider>
      <ErrorBoundary>
        {props.isPremadeListing ? <PremadeListing /> : <CharacterBuilder />}
      </ErrorBoundary>
    </BuilderProvider>
  );
}

export default CharacterBuilderContainer;
