import routes, { compatibilityV2Prefix } from "@/routes";
import { Route, Routes, useNavigate } from "react-router-dom";
import Layout from "./Layout";
import FindHappiness from "@/components/CompatibilityV2/pages/FindHappiness";
import StepperLayout from "./StepperLayout";
import Birthdate from "@/components/CompatibilityV2/pages/Birthdate";
import PalmsInformation from "@/components/CompatibilityV2/pages/PalmsInformation";
import NotFoundPage from "@/components/NotFoundPage";
import WhatAspects from "@/components/CompatibilityV2/pages/WhatAspects";
import RelationshipStatus from "@/components/CompatibilityV2/pages/RelationshipStatus";
import ElementResonates from "@/components/CompatibilityV2/pages/ElementResonates";
import FavoriteColor from "@/components/CompatibilityV2/pages/FavoriteColor";
import HeadOrHeart from "@/components/CompatibilityV2/pages/HeadOrHeart";
import HeadOrHeartResult from "@/components/CompatibilityV2/pages/HeadOrHeartResult";
import RelateFollowing from "@/components/CompatibilityV2/pages/RelateFollowing";
import LetScan from "@/components/CompatibilityV2/pages/LetScan";
import ScanInstruction from "@/components/CompatibilityV2/pages/ScanInstruction";
import Camera from "@/components/CompatibilityV2/pages/Camera";
import ScannedPhoto from "@/components/CompatibilityV2/pages/ScannedPhoto";
import Email from "@/components/CompatibilityV2/pages/Email";
import TrialChoice from "@/components/CompatibilityV2/pages/TrialChoice";
import TrialPayment from "@/components/CompatibilityV2/pages/TrialPayment";
import Payment from "@/components/CompatibilityV2/pages/Payment";
import { useEffect, useMemo } from "react";
import { useDispatch } from "react-redux";
import { actions } from "@/store";
import Gender from "@/components/CompatibilityV2/pages/Gender";
import CheckSubscriptionOutlet from "./CheckSubscriptionOutlet";
import TrialChoiceVideo from "@/components/CompatibilityV2/pages/TrialChoiceVideo";
import LayoutPersonalVideo from "./LayoutPersonalVideo";
import OnboardingPage from "@/components/pages/ABDesign/v1/pages/Onboarding";
import SaveOff from "@/components/CompatibilityV2/pages/SaveOff";
import SecretDiscount from "@/components/CompatibilityV2/pages/SecretDiscount";
import GenderPartner from "@/components/CompatibilityV2/pages/GenderPartner";
import BirthdatePartner from "@/components/CompatibilityV2/pages/BirthdatePartner";
import PalmsInformationPartner from "@/components/CompatibilityV2/pages/PalmsInformationPartner";
import DateEvent from "@/components/CompatibilityV2/pages/DateEvent";
import RomanticGestures from "@/components/CompatibilityV2/pages/RomanticGestures";
import CheckingPhone from "@/components/CompatibilityV2/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/CompatibilityV2/pages/TryApp";
import { useTheme } from "@/hooks/theme/useTheme";
import ScanHand from "@/components/CompatibilityV2/pages/ScanHand";
import { ELocalesPlacement } from "@/locales";
import { useFunnel } from "@/hooks/funnel/useFunnel";
import Review from "@/components/CompatibilityV2/pages/Review";
import {
  getSystemColorScheme,
  subscribeToSystemThemeChange,
} from "@/utils/Theme";
import CompatibilityTestPage from "@/components/CompatibilityV2/pages/CompatibilityTest";
import RelationshipStatusResult from "@/components/CompatibilityV2/pages/RelationshipStatusResult";
import FearInRelationship from "@/components/CompatibilityV2/pages/FearInRelationship";
import ImportantStep from "@/components/CompatibilityV2/pages/ImportantStep";
import WhoMatter from "@/components/CompatibilityV2/pages/WhoMatter";
import YourPriority from "@/components/CompatibilityV2/pages/YourPriority";
import PersonalizedRelationshipAnalysis from "@/components/CompatibilityV2/pages/PersonalizedRelationshipAnalysis";

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

function CompatibilityV2Routes() {
  const navigate = useNavigate();
  const dispatch = useDispatch();
  const { setTheme } = useTheme();

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

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

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

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

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

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

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

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

  useEffect(() => {
    const systemColorScheme = getSystemColorScheme();
    setTheme(systemColorScheme);

    const unsubscribe = subscribeToSystemThemeChange((theme) => {
      setTheme(theme);
    });

    return () => {
      unsubscribe?.();
    };
  }, [setTheme]);

  return (
    <Routes>
      <Route element={<PrivateOutlet />}>
        <Route element={<AdditionalPurchasesPalmistry />}>
          <Route
            path={removePrefix(routes.client.compatibilityV2SkipTrial())}
            element={<SkipTrial />}
          />
          <Route
            path={removePrefix(routes.client.compatibilityV2AddConsultant())}
            element={
              <AddConsultant
                funnel={ELocalesPlacement.CompatibilityV2}
                paymentPlacement="add_consultant"
                nextRoute={
                  availablePaths.add_guides
                    ? routes.client.compatibilityV2AddGuides()
                    : `${routes.client.getInformationPartner()}?path=back`
                }
              />
            }
          />
          <Route
            path={removePrefix(routes.client.compatibilityV2AddGuides())}
            element={
              <AddGuides
                funnel={ELocalesPlacement.CompatibilityV2}
                paymentPlacement="add_guides"
              />
            }
          />
        </Route>
      </Route>
      <Route
        element={
          <CheckSubscriptionOutlet
            subscribedReturnUrl={paymentSuccessNavigatePath}
          />
        }
      >
        <Route
          path={removePrefix(routes.client.compatibilityV2PaymentModal())}
          element={
            <PaymentPage
              funnel={ELocalesPlacement.CompatibilityV2}
              paymentPlacement="main"
              onError={onPaymentError}
              onSuccess={onPaymentSuccess}
              onBack={onBack}
              onPopState={onPopState}
            />
          }
        />
        <Route
          path={removePrefix(
            routes.client.compatibilityV2SecretDiscountPaymentModal()
          )}
          element={
            <PaymentPage
              funnel={ELocalesPlacement.CompatibilityV2}
              paymentPlacement="main_secret_discount"
              onError={onPaymentErrorDiscount}
              onSuccess={onPaymentSuccessDiscount}
            />
          }
        />
      </Route>
      <Route
        path={removePrefix(routes.client.compatibilityV2Onboarding())}
        element={<OnboardingPage />}
      />
      <Route
        path={removePrefix(routes.client.compatibilityV2SecretDiscount())}
        element={<SecretDiscount />}
      />
      <Route
        path={removePrefix(routes.client.compatibilityV2ScanHand())}
        element={<ScanHand />}
      />
      <Route
        path={removePrefix(routes.client.compatibilityV2Review())}
        element={<Review />}
      />
      <Route element={<Layout />}>
        <Route
          element={
            <CheckSubscriptionOutlet
              subscribedReturnUrl={paymentSuccessNavigatePath}
            />
          }
        >
          <Route element={<LayoutPersonalVideo />}>
            <Route
              path={removePrefix(routes.client.compatibilityV2Gender())}
              element={<Gender />}
            >
              <Route path="*" element={<Gender />} />
            </Route>
            <Route
              path={removePrefix(
                routes.client.compatibilityV2CompatibilityTest()
              )}
              element={<CompatibilityTestPage />}
            />
            <Route
              path={removePrefix(routes.client.compatibilityV2GenderPartner())}
              element={<GenderPartner />}
            />
            <Route
              path={removePrefix(routes.client.compatibilityV2Welcome())}
              element={<FindHappiness />}
            >
              <Route path="*" element={<FindHappiness />} />
            </Route>
            <Route
              path={removePrefix(
                routes.client.compatibilityV2RelationshipStatusResult()
              )}
              element={<RelationshipStatusResult />}
            />
            <Route
              path={removePrefix(
                routes.client.compatibilityV2PersonalizedRelationshipAnalysis()
              )}
              element={<PersonalizedRelationshipAnalysis />}
            />
            <Route element={<StepperLayout />}>
              <Route
                path={removePrefix(
                  routes.client.compatibilityV2FearInRelationship()
                )}
                element={<FearInRelationship />}
              />
              <Route
                path={removePrefix(
                  routes.client.compatibilityV2ImportantStep()
                )}
                element={<ImportantStep />}
              />
              <Route
                path={removePrefix(routes.client.compatibilityV2WhoMatter())}
                element={<WhoMatter />}
              />
              <Route
                path={removePrefix(routes.client.compatibilityV2YourPriority())}
                element={<YourPriority />}
              />
              <Route
                path={removePrefix(routes.client.compatibilityV2Birthdate())}
                element={<Birthdate />}
              />
              <Route
                path={removePrefix(
                  routes.client.compatibilityV2BirthdatePartner()
                )}
                element={<BirthdatePartner />}
              />
              <Route
                path={removePrefix(routes.client.compatibilityV2DateEvent())}
                element={<DateEvent />}
              />
              <Route
                path={removePrefix(
                  routes.client.compatibilityV2PalmsInformation()
                )}
                element={<PalmsInformation />}
              />
              <Route
                path={removePrefix(
                  routes.client.compatibilityV2PalmsInformationPartner()
                )}
                element={<PalmsInformationPartner />}
              />
              <Route
                path={removePrefix(routes.client.compatibilityV2WhatAspects())}
                element={<WhatAspects />}
              />
              <Route
                path={removePrefix(
                  routes.client.compatibilityV2RelationshipStatus()
                )}
                element={<RelationshipStatus />}
              />
              <Route
                path={removePrefix(
                  routes.client.compatibilityV2RomanticGestures()
                )}
                element={<RomanticGestures />}
              />
              <Route
                path={removePrefix(
                  routes.client.compatibilityV2CheckingPhone()
                )}
                element={<CheckingPhone />}
              />
              <Route
                path={removePrefix(
                  routes.client.compatibilityV2ElementResonates()
                )}
                element={<ElementResonates />}
              />
              <Route
                path={removePrefix(
                  routes.client.compatibilityV2FavoriteColor()
                )}
                element={<FavoriteColor />}
              />
              <Route
                path={removePrefix(routes.client.compatibilityV2HeadOrHeart())}
                element={<HeadOrHeart />}
              />
              <Route
                path={removePrefix(
                  routes.client.compatibilityV2HeadOrHeartResult()
                )}
                element={<HeadOrHeartResult />}
              />
              <Route
                path={removePrefix(
                  routes.client.compatibilityV2RelateFollowing()
                )}
                element={<RelateFollowing />}
              >
                <Route path=":questionId" element={<RelateFollowing />} />
              </Route>
              <Route
                path={removePrefix(routes.client.compatibilityV2Email())}
                element={<Email />}
              />
            </Route>
            <Route
              path={removePrefix(routes.client.compatibilityV2LetScan())}
              element={<LetScan />}
            />
            <Route
              path={removePrefix(
                routes.client.compatibilityV2ScanInstruction()
              )}
              element={<ScanInstruction />}
            />
            <Route
              path={removePrefix(routes.client.compatibilityV2Camera())}
              element={<Camera />}
            />
            <Route
              path={removePrefix(routes.client.compatibilityV2TrialChoice())}
              element={<TrialChoice />}
            />

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

            <Route
              path={removePrefix(routes.client.compatibilityV2TrialPayment())}
              element={<TrialPayment />}
            />
            <Route
              path={removePrefix(routes.client.compatibilityV2TryApp())}
              element={<TryApp />}
            />
            <Route
              path={removePrefix(routes.client.compatibilityV2Payment())}
              element={<Payment />}
            />
          </Route>
          <Route
            path={removePrefix(routes.client.compatibilityV2ScannedPhoto())}
            element={<ScannedPhoto />}
          />
          <Route
            path={removePrefix(routes.client.compatibilityV2SaveOff())}
            element={<SaveOff />}
          />
          <Route path="*" element={<NotFoundPage />} />
        </Route>
      </Route>
    </Routes>
  );
}

export default CompatibilityV2Routes;
