import styles from "./styles.module.scss";
import { useDispatch, useSelector } from "react-redux";
import { actions, selectors } from "@/store";
import { Gender } from "@/data";
// import Toast from "@/components/pages/ABDesign/v1/components/Toast";
import { useTranslations } from "@/hooks/translations";
import { ELocalesPlacement } from "@/locales";
import { useCallback, useEffect, useLayoutEffect, useState } from "react";
import { sleep } from "@/services/date";
import metricService, {
  useMetricABFlags,
} from "@/services/metric/metricService";
import { genders } from "@/components/pages/ABDesign/v1/data/genders";
import { Navigate, useNavigate, useSearchParams } from "react-router-dom";
import routes, { compatibilityV2Prefix } from "@/routes";
import { usePreloadImages } from "@/hooks/preload/images";
import { useSession } from "@/hooks/session/useSession";
import { EGender, ESourceAuthorization } from "@/api/resources/User";
import Loader, { LoaderColor } from "@/components/Loader";
import { EUnleashFlags, useUnleash } from "@/hooks/ab/unleash/useUnleash";
import GenderV0 from "./variants/GenderV0";
import GenderV1 from "./variants/GenderV1";
import GenderV2 from "./variants/GenderV2";
import { webviewToSystemBrowser } from "@/services/hacks/webviewToSystemBrowser";

function GenderPage() {
  const { translate } = useTranslations(ELocalesPlacement.CompatibilityV2);
  const dispatch = useDispatch();
  const navigate = useNavigate();
  const { createSession, updateSession } = useSession();
  const { checked: privacyPolicyChecked } = useSelector(
    selectors.selectPrivacyPolicy
  );

  const [searchParams] = useSearchParams();
  const noRedirectAB = searchParams.get("noRedirectAB") === "true";

  const { gender } = useSelector(selectors.selectQuestionnaire);
  const [isSelected, setIsSelected] = useState(false);

  usePreloadImages([`${compatibilityV2Prefix}/hand-with-eye.svg`]);

  const { flags, ready } = useMetricABFlags();

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

  const { variant: relationshipStatusPagePlacement = "v0" } = useUnleash({
    flag: EUnleashFlags.v2CompatibilityRelationshipStatusPagePlacement,
  });

  const { variant: reviewPage = "v0" } = useUnleash({
    flag: EUnleashFlags.v2CompatibilityReviewPage,
  });

  const { variant: pathToEnteringBirthdate = "hide" } = useUnleash({
    flag: EUnleashFlags.v2CompatibilityPathToEnteringBirthdate,
  });

  const pageType = flags?.genderPageType?.[0] || genderPageType || "v2";
  const genderButtonIcon = flags?.genderButtonIcon?.[0] || "hide";

  const localGenders = genders.map((gender) => ({
    id: gender.id,
    title: (
      <>
        {genderButtonIcon === "show" && (
          <span className={styles.genderIcon}>
            {gender.id === "male" ? "🙋‍♂️" : "🙋‍♀️"}
          </span>
        )}
        {translate(gender.id, undefined, ELocalesPlacement.V1)}
      </>
    ),
  }));

  useLayoutEffect(() => {
    const feature = location.pathname.replace(
      routes.client.compatibilityV2Gender(),
      ""
    );
    if (!!feature?.length) {
      dispatch(actions.userConfig.setFeature(feature));
    }
  }, [dispatch, location.pathname]);

  const selectGender = (_gender: Gender | null) => {
    dispatch(actions.privacyPolicy.updateChecked(true));
    setIsSelected(true);
    dispatch(actions.questionnaire.update({ gender: _gender?.id }));
  };

  const handleNext = useCallback(async () => {
    if (!gender) return;
    dispatch(actions.privacyPolicy.updateChecked(true));
    await sleep(1000);
    metricService.userParams({
      gender: genders.find((g) => g.id === gender)?.name,
    });

    const session = await createSession(
      ESourceAuthorization["aura.compatibility.v2"]
    );
    if (session?.sessionId?.length) {
      updateSession(
        {
          profile: {
            gender: EGender[gender as keyof typeof EGender],
          },
        },
        ESourceAuthorization["aura.compatibility.v2"],
        session.sessionId
      );
      metricService.userParams({
        sessionId: session.sessionId,
      });
    }
    if (relationshipStatusPagePlacement === "v2") {
      return navigate(routes.client.compatibilityV2RelationshipStatus());
    }

    if (["v1", "v2"].includes(reviewPage)) {
      return navigate(routes.client.compatibilityV2Review());
    }
    if (pathToEnteringBirthdate === "show") {
      return navigate(routes.client.compatibilityV2CompatibilityTest());
    }
    return navigate(routes.client.compatibilityV2Birthdate());
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [
    gender,
    navigate,
    reviewPage,
    pathToEnteringBirthdate,
    relationshipStatusPagePlacement,
    isReady,
  ]);

  useEffect(() => {
    if (privacyPolicyChecked && gender && isSelected) {
      webviewToSystemBrowser(["android", "ios"]);
      handleNext();
    }
  }, [gender, handleNext, isSelected, privacyPolicyChecked]);

  // useEffect(() => {
  //   if (pathToEnteringBirthdate === "show" && !pathToEnteringBirthdateShown) {
  //     dispatch(
  //       actions.compatibilityV2.update({ pathToEnteringBirthdateShown: true })
  //     );
  //     return navigate(routes.client.compatibilityV2CompatibilityTest());
  //   }
  // }, [
  //   dispatch,
  //   navigate,
  //   pathToEnteringBirthdate,
  //   pathToEnteringBirthdateShown,
  // ]);

  if (!ready || !isReady) return <Loader color={LoaderColor.Black} />;

  if (relationshipStatusPagePlacement === "v1" && !noRedirectAB) {
    return <Navigate to={routes.client.compatibilityV2RelationshipStatus()} />;
  }

  switch (pageType) {
    case "v0":
      return (
        <GenderV0
          localGenders={localGenders}
          gender={gender}
          selectGender={selectGender}
        />
      );
    case "v1":
      return (
        <GenderV1
          localGenders={localGenders}
          gender={gender}
          selectGender={selectGender}
        />
      );
    case "v2":
      return (
        <GenderV2
          localGenders={localGenders}
          gender={gender}
          selectGender={selectGender}
        />
      );
    default:
      return (
        <GenderV0
          localGenders={localGenders}
          gender={gender}
          selectGender={selectGender}
        />
      );
  }
}

export default GenderPage;
