import { TimePicker } from "@/components/DateTimePicker";
import styles from "./styles.module.css";
import { useDispatch, useSelector } from "react-redux";
import { actions, selectors } from "@/store";
import { useTranslations } from "@/hooks/translations";
import { useNavigate } from "react-router-dom";
import routes from "@/routes";
import { useState } from "react";
import QuestionnaireGreenButton from "../../../../ui/GreenButton";
import { ELocalesPlacement } from "@/locales";
import { useSession } from "@/hooks/session/useSession";
import { ESourceAuthorization } from "@/api/resources/User";

interface IBirthtimeCustomAnswerProps {
  affiliation?: "self" | "partner";
}

function BirthtimeCustomAnswer({
  affiliation = "self",
}: IBirthtimeCustomAnswerProps) {
  const { translate } = useTranslations(ELocalesPlacement.V1);
  const { updateSession } = useSession();
  const navigate = useNavigate();
  const dispatch = useDispatch();
  const selfBirthtime = useSelector(selectors.selectBirthtime);
  const questionnaire = useSelector(selectors.selectQuestionnaire);
  const birthtimeFromStore =
    affiliation === "self" ? selfBirthtime : questionnaire.partnerBirthtime;

  const birthdate =
    affiliation === "self"
      ? questionnaire.birthdate
      : questionnaire.partnerBirthdate;

  const [birthtime, setBirthtime] = useState(birthtimeFromStore);

  const handleChange = (_birthtime: string) => {
    setBirthtime(_birthtime);
    if (affiliation === "self") {
      dispatch(actions.form.addTime(_birthtime));
    }
  };

  const handleNext = async () => {
    if (affiliation === "self") {
      await updateSession({
        profile: {
          birthdate: `${birthdate} ${birthtime}`,
        },
      }, ESourceAuthorization["aura.main.new"]);
      dispatch(actions.questionnaire.update({ birthtime }));
      navigate(`${routes.client.questionnaireV1()}/profile/birthPlace`);
    }
    if (affiliation === "partner") {
      await updateSession({
        partner: {
          birthdate: `${birthdate} ${birthtime}`,
        },
      }, ESourceAuthorization["aura.main.new"]);
      dispatch(actions.questionnaire.update({ partnerBirthtime: birthtime }));
      navigate(
        `${routes.client.questionnaireV1()}/partnerProfile/partnerBirthPlace`
      );
    }
  };

  return (
    <div className={styles.container}>
      <TimePicker value={birthtime} onChange={handleChange} />

      <QuestionnaireGreenButton className={styles.button} onClick={handleNext}>
        {translate("next")}
      </QuestionnaireGreenButton>
      <img className={styles.image} src="/hourglassV1.webp" alt="hourglass" />
    </div>
  );
}

export default BirthtimeCustomAnswer;
