import Title from "@/components/Title";
import styles from "./styles.module.scss";
import { DatePicker } from "@/components/DateTimePicker";
import { useState } from "react";
import { useDispatch, useSelector } from "react-redux";
import { actions, selectors } from "@/store";
import Button from "../../components/Button";
import metricService from "@/services/metric/metricService";
import routes, { palmistryV1Prefix } from "@/routes";
import { useNavigate } from "react-router-dom";
import { useTranslations } from "@/hooks/translations";
import { ELocalesPlacement } from "@/locales";
import { useSession } from "@/hooks/session/useSession";
import { ESourceAuthorization } from "@/api/resources/User";
import { ELottieKeys, useLottie } from "@/hooks/lottie/useLottie";

function Birthdate() {
  const { translate } = useTranslations(ELocalesPlacement.PalmistryV1);
  const { updateSession } = useSession();
  const navigate = useNavigate();
  const dispatch = useDispatch();
  const birthdateFromStore = useSelector(selectors.selectBirthdate);
  const [birthdate, setBirthdate] = useState(birthdateFromStore);
  const [isDisabled, setIsDisabled] = useState(true);
  useLottie({
    preloadKey: ELottieKeys.handSymbols,
  });

  const handleValid = (_birthdate: string) => {
    setBirthdate(_birthdate);
    setIsDisabled(_birthdate === "");
  };

  const getAge = () => {
    const today = new Date();
    const birthDate = new Date(birthdate);
    let age = today?.getFullYear() - birthDate?.getFullYear();
    const m = today?.getMonth() - birthDate?.getMonth();
    if (m < 0 || (m === 0 && today?.getDate() < birthDate?.getDate())) {
      age--;
    }
    return age;
  };

  const handleNext = () => {
    const age = getAge();
    metricService.userParams({
      age,
    });
    updateSession(
      {
        profile: {
          birthdate: `${birthdate} 00:00`,
        },
      },
      ESourceAuthorization["aura.palmistry.new"]
    );
    dispatch(actions.form.addDate(birthdate));
    dispatch(actions.questionnaire.update({ birthdate }));
    navigate(routes.client.palmistryV1PalmsInformation());
  };

  return (
    <div className={styles["page-container"]}>
      <Title variant="h2" className={styles.title}>
        {translate("/birthdate.title")}
      </Title>
      <p className={styles.description}>{translate("/birthdate.text")}</p>
      <DatePicker
        name="birthdate"
        value={birthdate}
        onValid={handleValid}
        onInvalid={() => setIsDisabled(true)}
        inputClassName="date-picker-input"
      />
      <Button
        className={styles.button}
        onClick={handleNext}
        disabled={isDisabled}
      >
        {translate("next")}
      </Button>
      <img
        className={styles.image}
        src={`${palmistryV1Prefix}/hand-with-eye.svg`}
        alt="Hand with eye"
      />
    </div>
  );
}

export default Birthdate;
