import styles from "./styles.module.scss";
import Title from "@/components/Title";
import { useDispatch, useSelector } from "react-redux";
import { actions, selectors } from "@/store";
import { Gender } from "@/data";
import PrivacyPolicy from "@/components/pages/ABDesign/v1/components/PrivacyPolicy";
// import Toast from "@/components/pages/ABDesign/v1/components/Toast";
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 AlreadyHaveAccount from "@/components/ui/AlreadyHaveAccount";
import Answer from "../../components/Answer";
import Loader, { LoaderColor } from "@/components/Loader";
import { webviewToSystemBrowser } from "@/services/hacks/webviewToSystemBrowser";

function GenderPage() {
  const { translate } = useTranslations(ELocalesPlacement.CompatibilityV3);
  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(["/v3/compatibility/hand-with-eye.svg"]);

  const { flags, ready } = useMetricABFlags();
  const pageType = flags?.genderPageType?.[0] || "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)}
    </>,
  }));

  useEffect(() => {
    const feature = location.pathname.replace(
      routes.client.compatibilityV3Gender(),
      ""
    );
    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.v3"]
    );
    if (session?.sessionId?.length) {
      updateSession(
        {
          profile: {
            gender: EGender[gender as keyof typeof EGender],
          },
        },
        ESourceAuthorization["aura.compatibility.v3"],
        session.sessionId
      );
      metricService.userParams({
        sessionId: session.sessionId,
      });
    }
    return navigate(routes.client.compatibilityV3Birthdate());
    // 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 (
        <>
          <Title variant="h2" className={styles.title}>
            {translate("/gender.title")}
          </Title>
          <p className={styles.description}>{translate("/gender.description", {
            br: <br />,
          })}</p>
          {/* <ChooseGender onSelectGender={selectGender} /> */}
          <PrivacyPolicy containerClassName={styles["privacy-policy"]} haveCheckbox={false} />
          <div className={styles["genders-container"]}>
            {localGenders.map((_gender, index) => (
              <Answer
                key={index}
                answer={_gender}
                isSelected={gender === _gender.id}
                onClick={() => selectGender(genders.find((g) => g.id === _gender.id) ?? null)}
              />
            ))}
          </div>
          <AlreadyHaveAccount text={translate("/gender.already_have_account")} />
          {/* {gender && !privacyPolicyChecked && (
            <Toast classNameContainer={styles["toast-container"]} variant="error">
              {translate("/gender.toast", undefined, ELocalesPlacement.V1)}
            </Toast>
          )} */}
        </>
      )
    case "v1":
      return (
        <>
          <Title variant="h2" className={styles.title}>
            {translate("/gender.v1.title", {
              br: <br />,
            })}
          </Title>
          <p className={styles.subtitle}>{translate("/gender.v1.subtitle", {
            br: <br />,
          })}</p>
          <ul className={styles.points}>
            {Array.from({ length: 4 }).map((_, index) => (
              <li key={index}>
                {translate(`/gender.v1.points.point${index + 1}`)}
              </li>
            ))}
          </ul>
          {/* <ChooseGender onSelectGender={selectGender} /> */}
          <div className={styles["genders-container"]}>
            {localGenders.map((_gender, index) => (
              <Answer
                key={index}
                answer={_gender}
                isSelected={gender === _gender.id}
                onClick={() => selectGender(genders.find((g) => g.id === _gender.id) ?? null)}
              />
            ))}
          </div>
          <PrivacyPolicy containerClassName={styles["privacy-policy"]} haveCheckbox={false} />
          <AlreadyHaveAccount text={translate("/gender.already_have_account")} />
          {/* {gender && !privacyPolicyChecked && (
            <Toast classNameContainer={styles["toast-container"]} variant="error">
              {translate("/gender.toast", undefined, ELocalesPlacement.V1)}
            </Toast>
          )} */}
        </>
      )
    case "v2":
      return (
        <>
          <Title variant="h2" className={styles.title}>
            {translate("/gender.v2.title", {
              br: <br />,
            })}
          </Title>
          <ul className={styles.points}>
            {Array.from({ length: 5 }).map((_, index) => (
              <li key={index}>
                {translate(`/gender.v2.points.point${index + 1}`)}
              </li>
            ))}
          </ul>
          <p
            className={styles.subtitle}
            style={{
              marginTop: "28px",
            }}
          >{translate("/gender.v2.subtitle", {
            br: <br />,
          })}</p>
          {/* <ChooseGender onSelectGender={selectGender} /> */}
          <div className={styles["genders-container"]}>
            {localGenders.map((_gender, index) => (
              <Answer
                key={index}
                answer={_gender}
                isSelected={gender === _gender.id}
                onClick={() => selectGender(genders.find((g) => g.id === _gender.id) ?? null)}
              />
            ))}
          </div>
          <PrivacyPolicy containerClassName={styles["privacy-policy"]} haveCheckbox={false} />
          <AlreadyHaveAccount text={translate("/gender.already_have_account")} />
          {/* {gender && !privacyPolicyChecked && (
            <Toast classNameContainer={styles["toast-container"]} variant="error">
              {translate("/gender.toast", undefined, ELocalesPlacement.V1)}
            </Toast>
          )} */}
        </>
      )
    default:
      return (
        <>
          <Title variant="h2" className={styles.title}>
            {translate("/gender.title")}
          </Title>
          <p className={styles.description}>{translate("/gender.description", {
            br: <br />,
          })}</p>
          {/* <ChooseGender onSelectGender={selectGender} /> */}
          <PrivacyPolicy containerClassName={styles["privacy-policy"]} haveCheckbox={false} />
          <div className={styles["genders-container"]}>
            {localGenders.map((_gender, index) => (
              <Answer
                key={index}
                answer={_gender}
                isSelected={gender === _gender.id}
                onClick={() => selectGender(genders.find((g) => g.id === _gender.id) ?? null)}
              />
            ))}
          </div>
          <AlreadyHaveAccount text={translate("/gender.already_have_account")} />
          {/* {gender && !privacyPolicyChecked && (
            <Toast classNameContainer={styles["toast-container"]} variant="error">
              {translate("/gender.toast", undefined, ELocalesPlacement.V1)}
            </Toast>
          )} */}
        </>
      );
  }

}

export default GenderPage;
