import routes, { compatibilityV3Prefix } from "@/routes";
import { Route, Routes, useNavigate } from "react-router-dom";
import Layout from "./Layout";
import FindHappiness from "@/components/CompatibilityV3/pages/FindHappiness";
import StepperLayout from "./StepperLayout";
import Birthdate from "@/components/CompatibilityV3/pages/Birthdate";
import PalmsInformation from "@/components/CompatibilityV3/pages/PalmsInformation";
import NotFoundPage from "@/components/NotFoundPage";
import WhatAspects from "@/components/CompatibilityV3/pages/WhatAspects";
import RelationshipStatus from "@/components/CompatibilityV3/pages/RelationshipStatus";
import ElementResonates from "@/components/CompatibilityV3/pages/ElementResonates";
import FavoriteColor from "@/components/CompatibilityV3/pages/FavoriteColor";
import HeadOrHeart from "@/components/CompatibilityV3/pages/HeadOrHeart";
import HeadOrHeartResult from "@/components/CompatibilityV3/pages/HeadOrHeartResult";
import RelateFollowing from "@/components/CompatibilityV3/pages/RelateFollowing";
import LetScan from "@/components/CompatibilityV3/pages/LetScan";
import ScanInstruction from "@/components/CompatibilityV3/pages/ScanInstruction";
import Camera from "@/components/CompatibilityV3/pages/Camera";
import ScannedPhoto from "@/components/CompatibilityV3/pages/ScannedPhoto";
import Email from "@/components/CompatibilityV3/pages/Email";
import TrialChoice from "@/components/CompatibilityV3/pages/TrialChoice";
import TrialPayment from "@/components/CompatibilityV3/pages/TrialPayment";
import Payment from "@/components/CompatibilityV3/pages/Payment";
import { useEffect, useMemo } from "react";
import { useDispatch } from "react-redux";
import { actions } from "@/store";
import Gender from "@/components/CompatibilityV3/pages/Gender";
import CheckSubscriptionOutlet from "./CheckSubscriptionOutlet";
import TrialChoiceVideo from "@/components/CompatibilityV3/pages/TrialChoiceVideo";
import LayoutPersonalVideo from "./LayoutPersonalVideo";
import OnboardingPage from "@/components/pages/ABDesign/v1/pages/Onboarding";
import SaveOff from "@/components/CompatibilityV3/pages/SaveOff";
import SecretDiscount from "@/components/CompatibilityV3/pages/SecretDiscount";
import GenderPartner from "@/components/CompatibilityV3/pages/GenderPartner";
import BirthdatePartner from "@/components/CompatibilityV3/pages/BirthdatePartner";
import PalmsInformationPartner from "@/components/CompatibilityV3/pages/PalmsInformationPartner";
import DateEvent from "@/components/CompatibilityV3/pages/DateEvent";
import RomanticGestures from "@/components/CompatibilityV3/pages/RomanticGestures";
import CheckingPhone from "@/components/CompatibilityV3/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/CompatibilityV3/pages/TryApp";
import ChoosePlace from "@/components/CompatibilityV3/pages/ChoosePlace";
import CodeInstruction from "@/components/CompatibilityV3/pages/CodeInstruction";
import { useFunnel } from "@/hooks/funnel/useFunnel";
import { ELocalesPlacement } from "@/locales";

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

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

  const { funnelData } = useFunnel({
    funnel: ELocalesPlacement.CompatibilityV3,
    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.compatibilityV3SkipTrial();
    }
    if (availablePaths.add_consultant) {
      return routes.client.compatibilityV3AddConsultant();
    }
    if (availablePaths.add_guides) {
      return routes.client.compatibilityV3AddGuides();
    }
    return `${routes.client.getInformationPartner()}?path=back`;
  }, [availablePaths]);

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

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

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

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

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

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

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

  return (
    <Routes>
      <Route element={<PrivateOutlet />}>
        <Route element={<AdditionalPurchasesPalmistry />}>
          <Route
            path={removePrefix(routes.client.compatibilityV3SkipTrial())}
            element={<SkipTrial />}
          />
          <Route
            path={removePrefix(routes.client.compatibilityV3AddConsultant())}
            element={
              <AddConsultant
                funnel={ELocalesPlacement.CompatibilityV3}
                paymentPlacement="add_consultant"
                nextRoute={
                  availablePaths.add_guides
                    ? routes.client.compatibilityV3AddGuides()
                    : `${routes.client.getInformationPartner()}?path=back`
                }
              />
            }
          />
          <Route
            path={removePrefix(routes.client.compatibilityV3AddGuides())}
            element={
              <AddGuides
                funnel={ELocalesPlacement.CompatibilityV3}
                paymentPlacement="add_guides"
              />
            }
          />
        </Route>
      </Route>
      <Route
        element={
          <CheckSubscriptionOutlet
            subscribedReturnUrl={paymentSuccessNavigatePath}
          />
        }
      >
        <Route
          path={removePrefix(routes.client.compatibilityV3PaymentModal())}
          element={
            <PaymentPage
              funnel={ELocalesPlacement.CompatibilityV3}
              paymentPlacement="main"
              onError={onPaymentError}
              onSuccess={onPaymentSuccess}
              onBack={onBack}
              onPopState={onPopState}
            />
          }
        />
        <Route
          path={removePrefix(
            routes.client.compatibilityV3SecretDiscountPaymentModal()
          )}
          element={
            <PaymentPage
              funnel={ELocalesPlacement.CompatibilityV3}
              paymentPlacement="main_secret_discount"
              onError={onPaymentErrorDiscount}
              onSuccess={onPaymentSuccessDiscount}
            />
          }
        />
      </Route>
      <Route
        path={removePrefix(routes.client.compatibilityV3Onboarding())}
        element={<OnboardingPage />}
      />
      <Route
        path={removePrefix(routes.client.compatibilityV3SecretDiscount())}
        element={<SecretDiscount />}
      />
      <Route element={<Layout />}>
        <Route
          element={
            <CheckSubscriptionOutlet
              subscribedReturnUrl={paymentSuccessNavigatePath}
            />
          }
        >
          <Route element={<LayoutPersonalVideo />}>
            <Route
              path={removePrefix(routes.client.compatibilityV3Gender())}
              element={<Gender />}
            >
              <Route path="*" element={<Gender />} />
            </Route>
            <Route
              path={removePrefix(routes.client.compatibilityV3GenderPartner())}
              element={<GenderPartner />}
            />
            <Route
              path={removePrefix(routes.client.compatibilityV3Welcome())}
              element={<FindHappiness />}
            >
              <Route path="*" element={<FindHappiness />} />
            </Route>
            <Route element={<StepperLayout />}>
              <Route
                path={removePrefix(routes.client.compatibilityV3Birthdate())}
                element={<Birthdate />}
              />
              <Route
                path={removePrefix(
                  routes.client.compatibilityV3BirthdatePartner()
                )}
                element={<BirthdatePartner />}
              />
              <Route
                path={removePrefix(routes.client.compatibilityV3DateEvent())}
                element={<DateEvent />}
              />
              <Route
                path={removePrefix(
                  routes.client.compatibilityV3PalmsInformation()
                )}
                element={<PalmsInformation />}
              />
              <Route
                path={removePrefix(
                  routes.client.compatibilityV3PalmsInformationPartner()
                )}
                element={<PalmsInformationPartner />}
              />
              <Route
                path={removePrefix(routes.client.compatibilityV3WhatAspects())}
                element={<WhatAspects />}
              />
              <Route
                path={removePrefix(
                  routes.client.compatibilityV3RelationshipStatus()
                )}
                element={<RelationshipStatus />}
              />
              <Route
                path={removePrefix(
                  routes.client.compatibilityV3RomanticGestures()
                )}
                element={<RomanticGestures />}
              />
              <Route
                path={removePrefix(
                  routes.client.compatibilityV3CheckingPhone()
                )}
                element={<CheckingPhone />}
              />
              <Route
                path={removePrefix(
                  routes.client.compatibilityV3ElementResonates()
                )}
                element={<ElementResonates />}
              />
              <Route
                path={removePrefix(
                  routes.client.compatibilityV3FavoriteColor()
                )}
                element={<FavoriteColor />}
              />
              <Route
                path={removePrefix(routes.client.compatibilityV3HeadOrHeart())}
                element={<HeadOrHeart />}
              />
              <Route
                path={removePrefix(
                  routes.client.compatibilityV3HeadOrHeartResult()
                )}
                element={<HeadOrHeartResult />}
              />
              <Route
                path={removePrefix(
                  routes.client.compatibilityV3RelateFollowing()
                )}
                element={<RelateFollowing />}
              >
                <Route path=":questionId" element={<RelateFollowing />} />
              </Route>
              <Route
                path={removePrefix(routes.client.compatibilityV3Email())}
                element={<Email />}
              />
            </Route>
            <Route
              path={removePrefix(routes.client.compatibilityV3LetScan())}
              element={<LetScan />}
            />
            <Route
              path={removePrefix(
                routes.client.compatibilityV3ScanInstruction()
              )}
              element={<ScanInstruction />}
            />
            <Route
              path={removePrefix(routes.client.compatibilityV3Camera())}
              element={<Camera />}
            />
            <Route
              path={removePrefix(routes.client.compatibilityV3TrialChoice())}
              element={<TrialChoice />}
            />

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

            <Route
              path={removePrefix(routes.client.compatibilityV3TrialPayment())}
              element={<TrialPayment />}
            />
            <Route
              path={removePrefix(routes.client.compatibilityV3TryApp())}
              element={<TryApp />}
            />
            <Route
              path={removePrefix(routes.client.compatibilityV3Payment())}
              element={<Payment />}
            />
          </Route>
          <Route
            path={removePrefix(routes.client.compatibilityV3ScannedPhoto())}
            element={<ScannedPhoto />}
          />
          <Route
            path={removePrefix(routes.client.compatibilityV3ChoosePlace())}
            element={<ChoosePlace />}
          />
          <Route
            path={removePrefix(routes.client.compatibilityV3CodeInstruction())}
            element={<CodeInstruction />}
          />
          <Route
            path={removePrefix(routes.client.compatibilityV3SaveOff())}
            element={<SaveOff />}
          />
          <Route path="*" element={<NotFoundPage />} />
        </Route>
      </Route>
    </Routes>
  );
}

export default CompatibilityV3Routes;
