import routes, { palmistryV1Prefix } from "@/routes";
import { Route, Routes, useNavigate } from "react-router-dom";
import LayoutPalmistryV1 from "./LayoutPalmistryV1";
import FindHappiness from "@/components/PalmistryV1/pages/FindHappiness";
import StepperLayoutPalmistryV1 from "./StepperLayoutPalmistryV1";
import Birthdate from "@/components/PalmistryV1/pages/Birthdate";
import PalmsInformation from "@/components/PalmistryV1/pages/PalmsInformation";
import NotFoundPage from "@/components/NotFoundPage";
import WhatAspects from "@/components/PalmistryV1/pages/WhatAspects";
import RelationshipStatus from "@/components/PalmistryV1/pages/RelationshipStatus";
import ElementResonates from "@/components/PalmistryV1/pages/ElementResonates";
import FavoriteColor from "@/components/PalmistryV1/pages/FavoriteColor";
import HeadOrHeart from "@/components/PalmistryV1/pages/HeadOrHeart";
import HeadOrHeartResult from "@/components/PalmistryV1/pages/HeadOrHeartResult";
import RelateFollowing from "@/components/PalmistryV1/pages/RelateFollowing";
import LetScan from "@/components/PalmistryV1/pages/LetScan";
import ScanInstruction from "@/components/PalmistryV1/pages/ScanInstruction";
import Camera from "@/components/PalmistryV1/pages/Camera";
import ScannedPhoto from "@/components/PalmistryV1/pages/ScannedPhoto";
import Email from "@/components/PalmistryV1/pages/Email";
import TrialChoice from "@/components/PalmistryV1/pages/TrialChoice";
import TrialPayment from "@/components/PalmistryV1/pages/TrialPayment";
import Payment from "@/components/PalmistryV1/pages/Payment";
import { useEffect, useMemo } from "react";
import { useDispatch } from "react-redux";
import { actions } from "@/store";
import GenderPalmistry from "@/components/PalmistryV1/pages/GenderPalmistry";
import CheckSubscriptionOutlet from "./CheckSubscriptionOutlet";
import TrialChoiceVideo from "@/components/PalmistryV1/pages/TrialChoiceVideo";
import LayoutPersonalVideo from "./LayoutPersonalVideo";
import OnboardingPage from "@/components/pages/ABDesign/v1/pages/Onboarding";
import SaveOff from "@/components/PalmistryV1/pages/SaveOff";
import SecretDiscount from "@/components/PalmistryV1/pages/SecretDiscount";
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/PalmistryV1/pages/TryApp";
import { EUnleashFlags, useUnleash } from "@/hooks/ab/unleash/useUnleash";
import Loader, { LoaderColor } from "@/components/Loader";
import { useFunnel } from "@/hooks/funnel/useFunnel";
import { ELocalesPlacement } from "@/locales";

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

const availableUrlsDarkTheme = [
  routes.client.palmistryV1Welcome(),
  routes.client.palmistryV1Gender(),
  routes.client.palmistryV1Birthdate(),
  routes.client.palmistryV1PalmsInformation(),
  routes.client.palmistryV1WhatAspects(),
  routes.client.palmistryV1RelationshipStatus(),
  routes.client.palmistryV1ElementResonates(),
  routes.client.palmistryV1FavoriteColor(),
  routes.client.palmistryV1HeadOrHeart(),
  routes.client.palmistryV1HeadOrHeartResult(),
  routes.client.palmistryV1RelateFollowing(),
  routes.client.palmistryV1LetScan(),
  routes.client.palmistryV1ScanInstruction(),
  routes.client.palmistryV1Camera(),
  routes.client.palmistryV1ScannedPhoto(),
  routes.client.palmistryV1Email(),
];

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

  const { isReady, variant: darkThemePalmistryV1Variant } = useUnleash({
    flag: EUnleashFlags.darkThemePalmistryV1,
  });

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

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

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

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

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

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

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

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

  useEffect(() => {
    const isAvailableUrl = availableUrlsDarkTheme.reduce((acc, url) => {
      if (window.location.pathname.startsWith(url)) {
        return true;
      }
      return acc;
    }, false);

    if (isAvailableUrl && darkThemePalmistryV1Variant === "enabled") {
      document.body.classList.add("dark-theme");
    } else {
      document.body.classList.remove("dark-theme");
    }
  }, [window.location.pathname]);

  if (!isReady) {
    return (
      <div
        style={{
          display: "flex",
          justifyContent: "center",
          alignItems: "center",
          height: "100dvh",
        }}
      >
        <Loader color={LoaderColor.Black} />
      </div>
    );
  }

  return (
    <Routes>
      <Route element={<PrivateOutlet />}>
        <Route element={<AdditionalPurchasesPalmistry />}>
          <Route
            path={removePrefix(routes.client.palmistryV1SkipTrial())}
            element={<SkipTrial />}
          />
          <Route
            path={removePrefix(routes.client.palmistryV1AddConsultant())}
            element={
              <AddConsultant
                funnel={ELocalesPlacement.PalmistryV1}
                paymentPlacement="add_consultant"
                nextRoute={
                  availablePaths.add_guides
                    ? routes.client.palmistryV1AddGuides()
                    : `${routes.client.getInformationPartner()}?path=back`
                }
              />
            }
          />
          <Route
            path={removePrefix(routes.client.palmistryV1AddGuides())}
            element={
              <AddGuides
                funnel={ELocalesPlacement.PalmistryV1}
                paymentPlacement="add_guides"
              />
            }
          />
        </Route>
      </Route>
      <Route
        element={
          <CheckSubscriptionOutlet
            subscribedReturnUrl={paymentSuccessNavigatePath}
          />
        }
      >
        <Route
          path={removePrefix(routes.client.palmistryV1PaymentModal())}
          element={
            <PaymentPage
              funnel={ELocalesPlacement.PalmistryV1}
              paymentPlacement="main"
              onError={onPaymentError}
              onSuccess={onPaymentSuccess}
              onBack={onBack}
              onPopState={onPopState}
            />
          }
        />
        <Route
          path={removePrefix(
            routes.client.palmistryV1SecretDiscountPaymentModal()
          )}
          element={
            <PaymentPage
              funnel={ELocalesPlacement.PalmistryV1}
              paymentPlacement="main_secret_discount"
              onError={onPaymentErrorDiscount}
              onSuccess={onPaymentSuccessDiscount}
            />
          }
        />
      </Route>
      <Route
        path={removePrefix(routes.client.palmistryOnboardingV1())}
        element={<OnboardingPage />}
      />
      <Route
        path={removePrefix(routes.client.palmistryV1SecretDiscount())}
        element={<SecretDiscount />}
      />
      <Route element={<LayoutPalmistryV1 />}>
        <Route
          element={
            <CheckSubscriptionOutlet
              subscribedReturnUrl={paymentSuccessNavigatePath}
            />
          }
        >
          <Route element={<LayoutPersonalVideo />}>
            <Route
              path={removePrefix(routes.client.palmistryV1Gender())}
              element={<GenderPalmistry />}
            >
              <Route path="*" element={<GenderPalmistry />} />
            </Route>
            <Route
              path={removePrefix(routes.client.palmistryV1Welcome())}
              element={<FindHappiness />}
            >
              <Route path="*" element={<FindHappiness />} />
            </Route>
            <Route element={<StepperLayoutPalmistryV1 />}>
              <Route
                path={removePrefix(routes.client.palmistryV1Birthdate())}
                element={<Birthdate />}
              />
              <Route
                path={removePrefix(routes.client.palmistryV1PalmsInformation())}
                element={<PalmsInformation />}
              />
              <Route
                path={removePrefix(routes.client.palmistryV1WhatAspects())}
                element={<WhatAspects />}
              />
              <Route
                path={removePrefix(
                  routes.client.palmistryV1RelationshipStatus()
                )}
                element={<RelationshipStatus />}
              />
              <Route
                path={removePrefix(routes.client.palmistryV1ElementResonates())}
                element={<ElementResonates />}
              />
              <Route
                path={removePrefix(routes.client.palmistryV1FavoriteColor())}
                element={<FavoriteColor />}
              />
              <Route
                path={removePrefix(routes.client.palmistryV1HeadOrHeart())}
                element={<HeadOrHeart />}
              />
              <Route
                path={removePrefix(
                  routes.client.palmistryV1HeadOrHeartResult()
                )}
                element={<HeadOrHeartResult />}
              />
              <Route
                path={removePrefix(routes.client.palmistryV1RelateFollowing())}
                element={<RelateFollowing />}
              >
                <Route path=":questionId" element={<RelateFollowing />} />
              </Route>
              <Route
                path={removePrefix(routes.client.palmistryV1Email())}
                element={<Email />}
              />
            </Route>
            <Route
              path={removePrefix(routes.client.palmistryV1LetScan())}
              element={<LetScan />}
            />
            <Route
              path={removePrefix(routes.client.palmistryV1ScanInstruction())}
              element={<ScanInstruction />}
            />
            <Route
              path={removePrefix(routes.client.palmistryV1Camera())}
              element={<Camera />}
            />
            <Route
              path={removePrefix(routes.client.palmistryV1TrialChoice())}
              element={<TrialChoice />}
            />

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

            <Route
              path={removePrefix(routes.client.palmistryV1TrialPayment())}
              element={<TrialPayment />}
            />
            <Route
              path={removePrefix(routes.client.palmistryV1TryApp())}
              element={<TryApp />}
            />
            <Route
              path={removePrefix(routes.client.palmistryV1Payment())}
              element={<Payment />}
            />
          </Route>
          <Route
            path={removePrefix(routes.client.palmistryV1ScannedPhoto())}
            element={<ScannedPhoto />}
          />
          <Route
            path={removePrefix(routes.client.palmistryV1SaveOff())}
            element={<SaveOff />}
          />
          <Route path="*" element={<NotFoundPage />} />
        </Route>
      </Route>
    </Routes>
  );
}

export default PalmistryV1Routes;
