import { useEffect, useState } from "react";
import { useSelector } from "react-redux";

import { rulesEngineSelectors } from "@dndbeyond/character-rules-engine";

import { GuidedTour } from "~/components/GuidedTour";
import { useFeatureFlags } from "~/contexts/FeatureFlag";

import { getCharacterSheetSteps } from "./getCharacterSheetSteps";

export const CharacterSheetGuidedTour = ({ children, ...props }) => {
  const [step, setStep] = useState(0);
  const { characterSheetTourFlag } = useFeatureFlags();
  const isMobile = window.matchMedia("(max-width: 767px)").matches;
  const isTablet = window.matchMedia(
    "(min-width: 768px and max-width: 1023px)"
  ).matches;
  const isDesktop = window.matchMedia("(min-width: 1024px)").matches;
  const ready = useSelector(rulesEngineSelectors.isCharacterSheetReady);
  // const hasSpells = useSelector(rulesEngineSelectors.hasSpells);
  const [loading, setLoading] = useState(true);

  const setCurrentStep = (currentStep) => {
    switch (currentStep) {
      case 11: {
        if (isMobile) {
          const toggle = document.querySelector(
            "[class^='styles_navToggle']"
          ) as HTMLButtonElement;
          toggle?.click();
        }
        break;
      }
      case 13: {
        if (isTablet) {
          const toggle = document.querySelector(
            "[class^='styles_navToggle']"
          ) as HTMLButtonElement;
          toggle?.click();
        }
        break;
      }
      default:
        break;
    }
    setStep(currentStep);
  };

  useEffect(() => {
    // If character sheet has loaded, enable tour
    if (ready) setLoading(false);
  }, [ready]);

  return (
    <>
      {characterSheetTourFlag && !loading ? (
        <GuidedTour
          steps={getCharacterSheetSteps(false, isTablet, isDesktop)}
          step={step}
          setStep={setCurrentStep}
          showOnFirstLoad={true}
          cookieName="characterSheetGuidedTour"
          {...props}
        >
          {children}
        </GuidedTour>
      ) : (
        <>{children}</>
      )}
    </>
  );
};
