import styles from "./styles.module.css";
import Title from "@/components/Title";
import { Gender } from "@/data";
import { EProductKeys } from "@/data/products";
import routes from "@/routes";
import { actions, selectors } from "@/store";
import { useEffect, useMemo, useState } from "react";
import { useDispatch, useSelector } from "react-redux";
import { useLocation, useNavigate, useParams } from "react-router-dom";
import BackgroundTopBlob from "../../ui/BackgroundTopBlob";
import { useDynamicSize } from "@/hooks/useDynamicSize";
import Header from "../../components/Header";
import { genders } from "../../data/genders";
import PrivacyPolicy from "../../components/PrivacyPolicy";
import Toast from "../../components/Toast";
import { DotLottieReact } from "@lottiefiles/dotlottie-react";
import metricService, {
  useMetricABFlags,
} from "@/services/metric/metricService";
import { usePreloadImages } from "@/hooks/preload/images";
import { useTranslations } from "@/hooks/translations";
import { ELocalesPlacement } from "@/locales";
import { useSession } from "@/hooks/session/useSession";
import { EGender, ESourceAuthorization } from "@/api/resources/User";
import AlreadyHaveAccount from "@/components/ui/AlreadyHaveAccount";

interface IGenderPageProps {
  productKey?: EProductKeys;
}

function GenderPage({ productKey }: IGenderPageProps): JSX.Element {
  const { createSession, updateSession } = useSession();
  const { translate } = useTranslations(ELocalesPlacement.V1);
  const dispatch = useDispatch();
  const navigate = useNavigate();
  const location = useLocation();
  const { targetId } = useParams();
  const { width: pageWidth, elementRef: pageRef } = useDynamicSize({});
  const [selectedGender, setSelectedGender] = useState<Gender | null>(null);
  const { checked: privacyPolicyChecked } = useSelector(
    selectors.selectPrivacyPolicy
  );
  const { flags } = useMetricABFlags();
  const isNextPageMentioned = flags?.isNextPageMentioned?.[0];

  const preloadImages = useMemo(() => {
    const _preloadImages = [
      "/heart.webp",
      "https://d2ecldjic51fgm.cloudfront.net/pub/assets/aura/emoji/twohearts-bc5e3e37.png",
      "https://d2ecldjic51fgm.cloudfront.net/pub/assets/aura/emoji/ring-26f6592d.png",
      "https://d2ecldjic51fgm.cloudfront.net/pub/assets/aura/emoji/brokenheart-9e2ba6fb.png",
      "https://d2ecldjic51fgm.cloudfront.net/pub/assets/aura/emoji/thinkingface-aa0f3a72.png",
    ];
    if (isNextPageMentioned === "true") {
      _preloadImages.push("/new-york-times.png");
      _preloadImages.push("/partnersWithoutNewYorkTime.png");
    }
    return _preloadImages;
  }, [isNextPageMentioned]);

  usePreloadImages(preloadImages);

  useEffect(() => {
    const feature = location.pathname.replace("/v1/gender/", "");
    const isShowTryApp = targetId === "i";
    dispatch(actions.userConfig.addIsShowTryApp(isShowTryApp));
    dispatch(
      actions.userConfig.setFeature(
        feature.includes("/v1/gender") ? "" : feature
      )
    );
  }, [dispatch, location.pathname, targetId]);

  useEffect(() => {
    if (privacyPolicyChecked && selectedGender) {
      handleNext();
    }
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [privacyPolicyChecked, selectedGender]);

  const handleNext = async () => {
    if (!selectedGender) return;
    await new Promise((resolve) => setTimeout(resolve, 1000));
    dispatch(actions.questionnaire.update({ gender: selectedGender.id }));

    metricService.userParams({
      gender: selectedGender.name,
    });
    if (productKey === EProductKeys["palmistry.aura"]) {
      return navigate(routes.client.palmistryV1Birthdate());
    }
    if (productKey === EProductKeys["moons.pdf.aura"]) {
      return navigate(routes.client.epeBirthdate());
    }
    if (productKey === EProductKeys["chat.aura"]) {
      return navigate(routes.client.advisorChatBirthdate());
    }
    const session = await createSession(ESourceAuthorization["aura.main.new"]);
    if (session?.sessionId?.length) {
      await updateSession(
        {
          profile: {
            gender: EGender[selectedGender.id as keyof typeof EGender],
          },
        },
        ESourceAuthorization["aura.main.new"],
        session.sessionId
      );
      metricService.userParams({
        sessionId: session.sessionId,
      });
    }
    if (isNextPageMentioned === "true") {
      return navigate(routes.client.mentionedInV1());
    }
    return navigate(`/v1/questionnaire/profile/flowChoice`);
  };

  const selectGender = async (gender: Gender) => {
    if (selectedGender?.id === gender.id) {
      setSelectedGender(null);
    } else {
      setSelectedGender(gender);
    }
    if (!privacyPolicyChecked) {
      return;
    }
    handleNext();
  };

  const getButtonBGColor = (gender: Gender): string => {
    const { colorAssociation } = gender;
    if (Array.isArray(colorAssociation)) {
      return `linear-gradient(125.02deg, ${colorAssociation.join(", ")})`;
    }
    if (typeof colorAssociation === "string") {
      return colorAssociation;
    }
    return "#f5f5f5";
  };

  return (
    <section className={`${styles.page} page`} ref={pageRef}>
      <DotLottieReact
        style={{
          visibility: "hidden",
          height: 0,
          width: 0,
        }}
      />
      <BackgroundTopBlob
        className={styles["background-top-blob"]}
        width={pageWidth}
        height={306}
        fillPath="#0F1323"
      />
      <Header
        className={styles.header}
        classNameTitle={styles["header-title"]}
        isBackButtonVisible={false}
      />
      <Title variant="h2" className={styles.title}>
        {translate("/gender.title")}
      </Title>
      <span className={styles.description}>
        {translate("/gender.description")}
      </span>
      <Title variant="h3" className={styles["title-select"]}>
        {translate("/gender.select_your_gender")}
      </Title>
      <div className={styles["genders-container"]}>
        {genders.map((gender, index) => (
          <div
            className={`${styles["gender"]} ${selectedGender?.id === gender.id && styles["gender--selected"]
              }`}
            key={index}
            onClick={() => {
              selectGender(gender);
            }}
          >
            <span className={styles["gender__name"]}>
              {translate(gender.id)}
            </span>
            <button
              className={styles["image-container"]}
              style={{
                background: getButtonBGColor(gender),
              }}
            >
              <img
                src={gender.img}
                className={styles["gender__img"]}
                alt={gender.id}
              />
              <div className={styles["gender__slide-container"]}>
                <svg
                  width="27"
                  height="27"
                  viewBox="0 0 27 27"
                  fill="none"
                  xmlns="http://www.w3.org/2000/svg"
                  className={styles["gender__slide-element"]}
                >
                  <path
                    d="M13.5 0C17.0804 0 20.5142 1.42232 23.0459 3.95406C25.5777 6.4858 27 9.91958 27 13.5C27 15.2728 26.6508 17.0283 25.9724 18.6662C25.2939 20.3041 24.2995 21.7924 23.0459 23.0459C20.5142 25.5777 17.0804 27 13.5 27C9.91958 27 6.4858 25.5777 3.95406 23.0459C1.42232 20.5142 0 17.0804 0 13.5C0 11.7272 0.349188 9.97167 1.02763 8.33377C1.70606 6.69588 2.70047 5.20765 3.95406 3.95406C5.20765 2.70047 6.69588 1.70606 8.33377 1.02762C9.97167 0.349186 11.7272 0 13.5 0ZM10.8 21.6L18.9 13.5L10.8 5.4L8.91 7.29L15.12 13.5L8.91 19.71L10.8 21.6Z"
                    fill={gender.id === "male" ? "#85B6FF" : "#E4C6FF"}
                  />
                </svg>
              </div>
            </button>
          </div>
        ))}
      </div>
      <AlreadyHaveAccount />
      <PrivacyPolicy containerClassName={styles["privacy-policy"]} />
      {selectedGender && !privacyPolicyChecked && (
        <Toast classNameContainer={styles["toast-container"]} variant="error">
          {translate("/gender.toast")}
        </Toast>
      )}
    </section>
  );
}

export default GenderPage;
