import React, { useCallback, useEffect, useRef } from "react";
import { AnimatePresence, motion } from "framer-motion";
import { useLocation, useSearchParams } from "react-router-dom";

import "./steps-manager.css";

import Progressbar from "@/components/palmistry/progress-bar/progress-bar";
import PalmistryContainer from "@/components/palmistry/palmistry-container/palmistry-container";
import useSteps, { Step } from "@/hooks/palmistry/use-steps";
import StepWelcome from "@/components/palmistry/step-welcome/step-welcome";
import StepGender from "@/components/palmistry/step-gender/step-gender";
import StepBirthdate from "@/components/palmistry/step-birthdate/step-birthdate";
import StepPalmsHold from "@/components/palmistry/step-palms-hold/step-palms-hold";
import StepWish from "@/components/palmistry/step-wish/step-wish";
import StepRelationshipStatus from "@/components/palmistry/step-relationship-status/step-relationship-status";
import StepResonatedElement from "@/components/palmistry/step-resonated-element/step-resonated-element";
import StepColorYouLike from "@/components/palmistry/step-color-you-like/step-color-you-like";
import StepDecisions from "@/components/palmistry/step-decisions/step-decisions";
import StepGuidancePlan from "@/components/palmistry/step-guidance-plan/step-guidance-plan";
import StepPersonalStatement from "@/components/palmistry/step-personal-statement/step-personal-statement";
import StepScanInfo from "@/components/palmistry/step-scan-info/step-scan-info";
import StepUpload from "@/components/palmistry/step-upload/step-upload";
import StepScanPhoto from "@/components/palmistry/step-scan-photo/step-scan-photo";
import StepEmail from "@/components/palmistry/step-email/step-email";
import StepSubscriptionPlan from "@/components/palmistry/step-subscription-plan/step-subscription-plan";
import StepPaywall from "@/components/palmistry/step-paywall/step-paywall";
import PaymentScreen from "@/components/palmistry/payment-screen/payment-screen";
import DiscountScreen from "@/components/palmistry/discount-screen/discount-screen";
import PremiumBundleScreen from "@/components/palmistry/premium-bundle-screen/premium-bundle-screen";
import { useDispatch, useSelector } from "react-redux";
import { actions, selectors } from "@/store";
import routes from "@/routes";
import PersonalVideo from "@/components/pages/ABDesign/v1/pages/TrialPayment/components/PersonalVideo";
import styles from "./styles.module.scss";
import { useMetricABFlags } from "@/services/metric/metricService";

const PalmistryContainerWrapper = (props: {
  children: React.ReactNode;
  currentStep: Step;
}) => {
  return (
    <PalmistryContainer
      singleQuestion={[
        Step.Wish,
        Step.RelationshipStatus,
        Step.ResonatedElement,
        Step.ColorYouLike,
        Step.Decisions,
      ].includes(props.currentStep)}
      type={props.currentStep}
    >
      {props.children}
    </PalmistryContainer>
  );
};

const animationDuration = 0.2;

export default function StepsManager() {
  const dispatch = useDispatch();
  const steps = useSteps();
  const { pathname } = useLocation();
  const location = useLocation();
  const [searchParams] = useSearchParams();
  const fromRedesign = useSelector(selectors.selectPalmistryFromRedesign);
  const { gender } = useSelector(selectors.selectQuestionnaire);

  const [modalIsOpen, setModalIsOpen] = React.useState(false);
  const [isVisibleElements, setIsVisibleElements] = React.useState(
    location.pathname !== routes.client.palmistrySubscriptionPlan()
  );

  const showElementsTimer = useRef<NodeJS.Timeout>();
  const containerVideoRef = useRef<HTMLDivElement>(null);

  const { flags } = useMetricABFlags();
  const auraVideoTrial = flags?.auraVideoTrial?.[0];

  React.useLayoutEffect(() => {
    if (!steps.isInited || fromRedesign) return;
    steps.goFirstUnpassedStep(searchParams.toString());
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [steps.isInited]);

  const motionDivClassName = [
    "steps-manager__motion-div",
    modalIsOpen ? "steps-manager__motion-div_no-transform" : "",
  ];

  const nonSliderSteps = [Step.Payment, Step.Discount, Step.PremiumBundle];

  const showElements = useCallback(() => {
    showElementsTimer.current = setTimeout(() => {
      setIsVisibleElements(true);
    }, 29_000);
  }, [setIsVisibleElements]);

  useEffect(() => {
    if (location.pathname !== routes.client.palmistrySubscriptionPlan()) {
      dispatch(actions.personalVideo.updateIsVideoPlaying(false));
    }
  }, [dispatch, location.pathname]);

  return (
    <div className="steps-manager">
      {steps.currentNumber >= steps.progressBarRange[0] &&
        steps.currentNumber <= steps.progressBarRange[1] && (
          <Progressbar step={steps.currentNumber} />
        )}

      <main className="steps-manager__main">
        {(nonSliderSteps.includes(steps.current as Step) ||
          steps.current === Step.Paywall) && (
          <div
            style={
              steps.current === Step.Paywall
                ? { visibility: "hidden", position: "absolute" }
                : {}
            }
          >
            <PalmistryContainerWrapper currentStep={steps.current as Step}>
              {[Step.Paywall, Step.Payment].includes(steps.current as Step) && (
                <PaymentScreen />
              )}
              {steps.current === Step.Discount && <DiscountScreen />}
              {steps.current === Step.PremiumBundle && <PremiumBundleScreen />}
            </PalmistryContainerWrapper>
          </div>
        )}

        {!nonSliderSteps.includes(steps.current as Step) && (
          <AnimatePresence mode="wait" initial={false}>
            <motion.div
              className={motionDivClassName.join(" ")}
              key={pathname}
              initial="pageInitial"
              animate="pageAnimate"
              exit="pageExit"
              variants={{
                pageInitial: {
                  transform: "translateX(100vw)",
                  width: "100%",
                },
                pageAnimate: {
                  transform: "translateX(0)",
                  width: "100%",
                },
                pageExit: {
                  transform: "translateX(-200vw)",
                  opacity: 0,
                  width: "100%",
                },
              }}
              transition={{
                duration: animationDuration,
                ease: "linear",
              }}
            >
              <PalmistryContainerWrapper currentStep={steps.current as Step}>
                <PersonalVideo
                  gender={gender}
                  url={"/trial-choice-palmistry.mp4"}
                  classNameContainer={
                    location.pathname !==
                      routes.client.palmistrySubscriptionPlan() ||
                    auraVideoTrial !== "on"
                      ? styles["personal-video-hide"]
                      : ""
                  }
                  isVisibleControllers={isVisibleElements}
                  onVideoStart={showElements}
                  containerRef={containerVideoRef}
                  isAutoPlay={
                    location.pathname ===
                      routes.client.palmistrySubscriptionPlan() &&
                    auraVideoTrial === "on"
                  }
                />
                {steps.current === Step.Welcome && <StepWelcome />}

                {steps.current === Step.Gender && <StepGender />}

                {steps.current === Step.Birthdate && <StepBirthdate />}

                {steps.current === Step.PalmsHold && <StepPalmsHold />}

                {steps.current === Step.Wish && <StepWish />}

                {steps.current === Step.RelationshipStatus && (
                  <StepRelationshipStatus />
                )}

                {steps.current === Step.ResonatedElement && (
                  <StepResonatedElement />
                )}

                {steps.current === Step.ColorYouLike && <StepColorYouLike />}

                {steps.current === Step.Decisions && <StepDecisions />}

                {steps.current === Step.GuidancePlan && <StepGuidancePlan />}

                {steps.current === Step.PersonalStatement && (
                  <StepPersonalStatement />
                )}

                {steps.current === Step.ScanInfo && <StepScanInfo />}

                {steps.current === Step.Upload && (
                  <StepUpload onOpenModal={setModalIsOpen} />
                )}

                {steps.current === Step.ScanPhoto && <StepScanPhoto />}

                {steps.current === Step.Email && <StepEmail />}

                {steps.current === Step.SubscriptionPlan && (
                  <StepSubscriptionPlan
                    containerVideoRef={containerVideoRef}
                    isVisibleElements={isVisibleElements}
                  />
                )}

                {steps.current === Step.Paywall && <StepPaywall />}
              </PalmistryContainerWrapper>
            </motion.div>
          </AnimatePresence>
        )}
      </main>
    </div>
  );
}
