import routes, { compatibilityV4Prefix } from "@/routes";
import { Route, Routes, useNavigate } from "react-router-dom";
import Layout from "./Layout";
import FindHappiness from "@/components/CompatibilityV4/pages/FindHappiness";
import StepperLayout from "./StepperLayout";
import Birthdate from "@/components/CompatibilityV4/pages/Birthdate";
import PalmsInformation from "@/components/CompatibilityV4/pages/PalmsInformation";
import NotFoundPage from "@/components/NotFoundPage";
import WhatAspects from "@/components/CompatibilityV4/pages/WhatAspects";
import RelationshipStatus from "@/components/CompatibilityV4/pages/RelationshipStatus";
import ElementResonates from "@/components/CompatibilityV4/pages/ElementResonates";
import FavoriteColor from "@/components/CompatibilityV4/pages/FavoriteColor";
import HeadOrHeart from "@/components/CompatibilityV4/pages/HeadOrHeart";
import HeadOrHeartResult from "@/components/CompatibilityV4/pages/HeadOrHeartResult";
import RelateFollowing from "@/components/CompatibilityV4/pages/RelateFollowing";
import LetScan from "@/components/CompatibilityV4/pages/LetScan";
import ScanInstruction from "@/components/CompatibilityV4/pages/ScanInstruction";
import Camera from "@/components/CompatibilityV4/pages/Camera";
import ScannedPhoto from "@/components/CompatibilityV4/pages/ScannedPhoto";
import Email from "@/components/CompatibilityV4/pages/Email";
import TrialChoice from "@/components/CompatibilityV4/pages/TrialChoice";
import TrialPayment from "@/components/CompatibilityV4/pages/TrialPayment";
import Payment from "@/components/CompatibilityV4/pages/Payment";
import { useEffect, useMemo } from "react";
import { useDispatch } from "react-redux";
import { actions } from "@/store";
import Gender from "@/components/CompatibilityV4/pages/Gender";
import CheckSubscriptionOutlet from "./CheckSubscriptionOutlet";
import TrialChoiceVideo from "@/components/CompatibilityV4/pages/TrialChoiceVideo";
import LayoutPersonalVideo from "./LayoutPersonalVideo";
import OnboardingPage from "@/components/pages/ABDesign/v1/pages/Onboarding";
import SaveOff from "@/components/CompatibilityV4/pages/SaveOff";
import SecretDiscount from "@/components/CompatibilityV4/pages/SecretDiscount";
import GenderPartner from "@/components/CompatibilityV4/pages/GenderPartner";
import BirthdatePartner from "@/components/CompatibilityV4/pages/BirthdatePartner";
import PalmsInformationPartner from "@/components/CompatibilityV4/pages/PalmsInformationPartner";
import DateEvent from "@/components/CompatibilityV4/pages/DateEvent";
import RomanticGestures from "@/components/CompatibilityV4/pages/RomanticGestures";
import CheckingPhone from "@/components/CompatibilityV4/pages/CheckingPhone";
import { PrivateOutlet } from "@/components/App";
import AdditionalPurchasesPalmistry from "@/components/palmistry/AdditionalPurchases";
import SkipTrial from "@/components/palmistry/AdditionalPurchases/pages/SkipTrial";
import AddConsultant from "@/components/palmistry/AdditionalPurchases/pages/AddConsultant";
import AddGuides from "@/components/palmistry/AdditionalPurchases/pages/AddGuides";
import PaymentPage from "@/components/Payment/nmi/PaymentPage";
import TryApp from "@/components/CompatibilityV4/pages/TryApp";
import ChoosePlace from "@/components/CompatibilityV4/pages/ChoosePlace";
import CodeInstruction from "@/components/CompatibilityV4/pages/CodeInstruction";
import RelationshipStatusResult from "@/components/CompatibilityV4/pages/RelationshipStatusResult";
import CalculateInAdvance from "@/components/CompatibilityV4/pages/CalculateInAdvance";
import CalculateInAdvanceResult from "@/components/CompatibilityV4/pages/CalculateInAdvanceResult";
import Birthplace from "@/components/CompatibilityV4/pages/Birthplace";
import Birthtime from "@/components/CompatibilityV4/pages/Birthtime";
import YourAnalysis from "@/components/CompatibilityV4/pages/YourAnalysis";
import ResultAnalysis from "@/components/CompatibilityV4/pages/ResultAnalysis";
import ResultAnalysisResult from "@/components/CompatibilityV4/pages/ResultAnalysisResult";
import ReviewPage from "@/components/CompatibilityV4/pages/Review";
import PartnerSimilarity from "@/components/CompatibilityV4/pages/PartnerSimilarity";
import BirthplacePartner from "@/components/CompatibilityV4/pages/BirthplacePartner";
import PartnerAnalysis from "@/components/CompatibilityV4/pages/PartnerAnalysis";
import AlmostThere from "@/components/CompatibilityV4/pages/AlmostThere";
import ComplexRelationshipAspect from "@/components/CompatibilityV4/pages/ComplexRelationshipAspect";
import StressResponse from "@/components/CompatibilityV4/pages/StressResponse";
import StressResponseResult from "@/components/CompatibilityV4/pages/StressResponseResult";
import WhatAddToAnalysis from "@/components/CompatibilityV4/pages/WhatAddToAnalysis";
import Loading from "@/components/CompatibilityV4/pages/Loading";
import PartnerPassword from "@/components/CompatibilityV4/pages/PartnerPassword";
import YourFear from "@/components/CompatibilityV4/pages/YourFear";
import YourInclination from "@/components/CompatibilityV4/pages/YourInclination";
import PotentialPartnerName from "@/components/CompatibilityV4/pages/PotentialPartnerName";
import PotentialPartnerBirthdate from "@/components/CompatibilityV4/pages/PotentialPartnerBirthdate";
import FormerPartnerName from "@/components/CompatibilityV4/pages/FormerPartnerName";
import FormerPartnerBirthdate from "@/components/CompatibilityV4/pages/FormerPartnerBirthdate";
import { useFunnel } from "@/hooks/funnel/useFunnel";
import { ELocalesPlacement } from "@/locales";

const removePrefix = (path: string) => path.replace(compatibilityV4Prefix, "");

function CompatibilityV4Routes() {
  const navigate = useNavigate();
  const dispatch = useDispatch();

  const { funnelData } = useFunnel({
    funnel: ELocalesPlacement.CompatibilityV4,
    paymentPlacement: "",
  });

  const availablePaths = useMemo(() => {
    if (!funnelData) return {};
    return {
      main: "main" in funnelData.payment,
      main_secret_discount: "main_secret_discount" in funnelData.payment,
      add_consultant: "add_consultant" in funnelData.payment,
      add_guides: "add_guides" in funnelData.payment,
      skip_trial: "skip_trial" in funnelData.payment,
    };
  }, [funnelData]);

  const paymentSuccessNavigatePath = useMemo(() => {
    if (availablePaths.skip_trial) {
      return routes.client.compatibilityV4SkipTrial();
    }
    if (availablePaths.add_consultant) {
      return routes.client.compatibilityV4AddConsultant();
    }
    if (availablePaths.add_guides) {
      return routes.client.compatibilityV4AddGuides();
    }
    return `${routes.client.getInformationPartner()}?path=back`;
  }, [availablePaths]);

  useEffect(() => {
    dispatch(actions.compatibilityV4.update({ fromRedesign: true }));
  }, [dispatch]);

  function onPaymentError(error?: string | null): void {
    if (error === "Product not found") {
      return navigate(routes.client.compatibilityV4TrialChoice());
    }
  }

  function onPaymentSuccess(): void {
    setTimeout(() => {
      return navigate(paymentSuccessNavigatePath);
    }, 1500);
  }

  function onBack(): void {
    if (!availablePaths.main_secret_discount) return;
    navigate(routes.client.compatibilityV4SaveOff());
  }

  function onPopState(): void {
    if (!availablePaths.main_secret_discount) return;
    if (
      document.location.toString() ===
        `${window.location.origin}${routes.client.compatibilityV4Payment()}` ||
      document.location.toString() ===
        `${
          window.location.origin
        }${routes.client.compatibilityV4TrialPayment()}`
    ) {
      navigate(routes.client.compatibilityV4SaveOff());
    }
  }

  function onPaymentErrorDiscount(error?: string | null): void {
    if (error === "Product not found") {
      return navigate(routes.client.compatibilityV4SecretDiscount());
    }
  }

  function onPaymentSuccessDiscount(): void {
    setTimeout(() => {
      navigate(paymentSuccessNavigatePath);
    }, 1500);
  }

  return (
    <Routes>
      <Route element={<PrivateOutlet />}>
        <Route element={<AdditionalPurchasesPalmistry />}>
          <Route
            path={removePrefix(routes.client.compatibilityV4SkipTrial())}
            element={<SkipTrial />}
          />
          <Route
            path={removePrefix(routes.client.compatibilityV4AddConsultant())}
            element={
              <AddConsultant
                funnel={ELocalesPlacement.CompatibilityV4}
                paymentPlacement="add_consultant"
                nextRoute={
                  availablePaths.add_guides
                    ? routes.client.compatibilityV4AddGuides()
                    : `${routes.client.getInformationPartner()}?path=back`
                }
              />
            }
          />
          <Route
            path={removePrefix(routes.client.compatibilityV4AddGuides())}
            element={
              <AddGuides
                funnel={ELocalesPlacement.CompatibilityV4}
                paymentPlacement="add_guides"
              />
            }
          />
        </Route>
      </Route>
      <Route
        element={
          <CheckSubscriptionOutlet
            subscribedReturnUrl={paymentSuccessNavigatePath}
          />
        }
      >
        <Route
          path={removePrefix(routes.client.compatibilityV4PaymentModal())}
          element={
            <PaymentPage
              funnel={ELocalesPlacement.CompatibilityV4}
              paymentPlacement="main"
              onError={onPaymentError}
              onSuccess={onPaymentSuccess}
              onBack={onBack}
              onPopState={onPopState}
            />
          }
        />
        <Route
          path={removePrefix(
            routes.client.compatibilityV4SecretDiscountPaymentModal()
          )}
          element={
            <PaymentPage
              funnel={ELocalesPlacement.CompatibilityV4}
              paymentPlacement="main_secret_discount"
              onError={onPaymentErrorDiscount}
              onSuccess={onPaymentSuccessDiscount}
            />
          }
        />
      </Route>
      <Route
        path={removePrefix(routes.client.compatibilityV4Onboarding())}
        element={<OnboardingPage />}
      />
      <Route
        path={removePrefix(routes.client.compatibilityV4SecretDiscount())}
        element={<SecretDiscount />}
      />
      <Route element={<Layout />}>
        <Route
          element={
            <CheckSubscriptionOutlet
              subscribedReturnUrl={paymentSuccessNavigatePath}
            />
          }
        >
          <Route
            path={removePrefix(
              routes.client.compatibilityV4RelationshipStatusResult()
            )}
            element={<RelationshipStatusResult />}
          />
          <Route
            path={removePrefix(
              routes.client.compatibilityV4CalculateInAdvanceResult()
            )}
            element={<CalculateInAdvanceResult />}
          />
          <Route
            path={removePrefix(
              routes.client.compatibilityV4ResultAnalysisResult()
            )}
            element={<ResultAnalysisResult />}
          />
          <Route
            path={removePrefix(
              routes.client.compatibilityV4StressResponseResult()
            )}
            element={<StressResponseResult />}
          />
          <Route element={<LayoutPersonalVideo />}>
            <Route
              path={removePrefix(routes.client.compatibilityV4Gender())}
              element={<Gender />}
            >
              <Route path="*" element={<Gender />} />
            </Route>
            <Route
              path={removePrefix(routes.client.compatibilityV4Welcome())}
              element={<FindHappiness />}
            >
              <Route path="*" element={<FindHappiness />} />
            </Route>
            <Route
              path={removePrefix(
                routes.client.compatibilityV4HeadOrHeartResult()
              )}
              element={<HeadOrHeartResult />}
            />
            <Route
              path={removePrefix(routes.client.compatibilityV4Loading())}
              element={<Loading />}
            />
            <Route element={<StepperLayout />}>
              <Route
                path={removePrefix(
                  routes.client.compatibilityV4WhatAddToAnalysis()
                )}
                element={<WhatAddToAnalysis />}
              />
              <Route
                path={removePrefix(
                  routes.client.compatibilityV4PotentialPartnerName()
                )}
                element={<PotentialPartnerName />}
              />
              <Route
                path={removePrefix(
                  routes.client.compatibilityV4PotentialPartnerBirthdate()
                )}
                element={<PotentialPartnerBirthdate />}
              />
              <Route
                path={removePrefix(
                  routes.client.compatibilityV4FormerPartnerName()
                )}
                element={<FormerPartnerName />}
              />
              <Route
                path={removePrefix(
                  routes.client.compatibilityV4FormerPartnerBirthdate()
                )}
                element={<FormerPartnerBirthdate />}
              />
              <Route
                path={removePrefix(
                  routes.client.compatibilityV4GenderPartner()
                )}
                element={<GenderPartner />}
              />
              <Route
                path={removePrefix(routes.client.compatibilityV4Birthdate())}
                element={<Birthdate />}
              />
              <Route
                path={removePrefix(routes.client.compatibilityV4Birthplace())}
                element={<Birthplace />}
              />
              <Route
                path={removePrefix(
                  routes.client.compatibilityV4BirthplacePartner()
                )}
                element={<BirthplacePartner />}
              />
              <Route
                path={removePrefix(routes.client.compatibilityV4Birthtime())}
                element={<Birthtime />}
              />
              <Route
                path={removePrefix(routes.client.compatibilityV4YourAnalysis())}
                element={<YourAnalysis />}
              />
              <Route
                path={removePrefix(
                  routes.client.compatibilityV4PartnerAnalysis()
                )}
                element={<PartnerAnalysis />}
              />
              <Route
                path={removePrefix(
                  routes.client.compatibilityV4ResultAnalysis()
                )}
                element={<ResultAnalysis />}
              />
              <Route
                path={removePrefix(
                  routes.client.compatibilityV4PartnerSimilarity()
                )}
                element={<PartnerSimilarity />}
              />
              <Route
                path={removePrefix(routes.client.compatibilityV4Review())}
                element={<ReviewPage />}
              />
              <Route
                path={removePrefix(
                  routes.client.compatibilityV4BirthdatePartner()
                )}
                element={<BirthdatePartner />}
              />
              <Route
                path={removePrefix(routes.client.compatibilityV4DateEvent())}
                element={<DateEvent />}
              />
              <Route
                path={removePrefix(
                  routes.client.compatibilityV4PalmsInformation()
                )}
                element={<PalmsInformation />}
              />
              <Route
                path={removePrefix(
                  routes.client.compatibilityV4PalmsInformationPartner()
                )}
                element={<PalmsInformationPartner />}
              />
              <Route
                path={removePrefix(routes.client.compatibilityV4WhatAspects())}
                element={<WhatAspects />}
              />
              <Route
                path={removePrefix(
                  routes.client.compatibilityV4RelationshipStatus()
                )}
                element={<RelationshipStatus />}
              />
              <Route
                path={removePrefix(
                  routes.client.compatibilityV4CalculateInAdvance()
                )}
                element={<CalculateInAdvance />}
              />
              <Route
                path={removePrefix(routes.client.compatibilityV4AlmostThere())}
                element={<AlmostThere />}
              />
              <Route
                path={removePrefix(
                  routes.client.compatibilityV4RomanticGestures()
                )}
                element={<RomanticGestures />}
              />
              <Route
                path={removePrefix(
                  routes.client.compatibilityV4CheckingPhone()
                )}
                element={<CheckingPhone />}
              />
              <Route
                path={removePrefix(
                  routes.client.compatibilityV4PartnerPassword()
                )}
                element={<PartnerPassword />}
              />
              <Route
                path={removePrefix(
                  routes.client.compatibilityV4YourInclination()
                )}
                element={<YourInclination />}
              />
              <Route
                path={removePrefix(routes.client.compatibilityV4YourFear())}
                element={<YourFear />}
              />
              <Route
                path={removePrefix(
                  routes.client.compatibilityV4ComplexRelationshipAspect()
                )}
                element={<ComplexRelationshipAspect />}
              />
              <Route
                path={removePrefix(
                  routes.client.compatibilityV4StressResponse()
                )}
                element={<StressResponse />}
              />
              <Route
                path={removePrefix(
                  routes.client.compatibilityV4ElementResonates()
                )}
                element={<ElementResonates />}
              />
              <Route
                path={removePrefix(
                  routes.client.compatibilityV4FavoriteColor()
                )}
                element={<FavoriteColor />}
              />
              <Route
                path={removePrefix(routes.client.compatibilityV4HeadOrHeart())}
                element={<HeadOrHeart />}
              />
              <Route
                path={removePrefix(
                  routes.client.compatibilityV4RelateFollowing()
                )}
                element={<RelateFollowing />}
              >
                <Route path=":questionId" element={<RelateFollowing />} />
              </Route>
              <Route
                path={removePrefix(routes.client.compatibilityV4Email())}
                element={<Email />}
              />
            </Route>
            <Route
              path={removePrefix(routes.client.compatibilityV4LetScan())}
              element={<LetScan />}
            />
            <Route
              path={removePrefix(
                routes.client.compatibilityV4ScanInstruction()
              )}
              element={<ScanInstruction />}
            />
            <Route
              path={removePrefix(routes.client.compatibilityV4Camera())}
              element={<Camera />}
            />
            <Route
              path={removePrefix(routes.client.compatibilityV4TrialChoice())}
              element={<TrialChoice />}
            />

            <Route
              path={removePrefix(
                routes.client.compatibilityV4TrialChoiceVideo()
              )}
              element={<TrialChoiceVideo />}
            />

            <Route
              path={removePrefix(routes.client.compatibilityV4TrialPayment())}
              element={<TrialPayment />}
            />
            <Route
              path={removePrefix(routes.client.compatibilityV4TryApp())}
              element={<TryApp />}
            />
            <Route
              path={removePrefix(routes.client.compatibilityV4Payment())}
              element={<Payment />}
            />
          </Route>
          <Route
            path={removePrefix(routes.client.compatibilityV4ScannedPhoto())}
            element={<ScannedPhoto />}
          />
          <Route
            path={removePrefix(routes.client.compatibilityV4ChoosePlace())}
            element={<ChoosePlace />}
          />
          <Route
            path={removePrefix(routes.client.compatibilityV4CodeInstruction())}
            element={<CodeInstruction />}
          />
          <Route
            path={removePrefix(routes.client.compatibilityV4SaveOff())}
            element={<SaveOff />}
          />
          <Route path="*" element={<NotFoundPage />} />
        </Route>
      </Route>
    </Routes>
  );
}

export default CompatibilityV4Routes;
