import styles from "./styles.module.scss";
import { useDispatch, useSelector } from "react-redux";
import { actions, selectors } from "@/store";
import { Gender } from "@/data";
import { useTranslations } from "@/hooks/translations";
import { ELocalesPlacement } from "@/locales";
import { useCallback, useEffect, 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 { useNavigate } from "react-router-dom";
import routes 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 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.CompatibilityV4);
  const dispatch = useDispatch();
  const navigate = useNavigate();
  const { createSession, updateSession } = useSession();
  const { checked: privacyPolicyChecked } = useSelector(
    selectors.selectPrivacyPolicy
  );

  const { gender } = useSelector(selectors.selectQuestionnaire);
  const [isSelected, setIsSelected] = useState(false);
  usePreloadImages(["/v1/palmistry/hand-with-eye.svg"]);

  const { flags, ready } = useMetricABFlags();
  const pageType = flags?.genderPageType?.[0] || "v2";
  const genderButtonIcon = flags?.genderButtonIcon?.[0] || "show";

  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)}
    </>,
  }));

  useEffect(() => {
    const feature = location.pathname.replace(
      routes.client.compatibilityV4Gender(),
      ""
    );
    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.v4"]
    );
    if (session?.sessionId?.length) {
      updateSession(
        {
          profile: {
            gender: EGender[gender as keyof typeof EGender],
          },
        },
        ESourceAuthorization["aura.compatibility.v4"],
        session.sessionId
      );
      metricService.userParams({
        sessionId: session.sessionId,
      });
    }
    return navigate(routes.client.compatibilityV4RelationshipStatus());
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [gender, navigate]);

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

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

  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;
