import { TimePicker } from "@/components/DateTimePicker";
import styles from "./styles.module.css";
import { useDispatch, useSelector } from "react-redux";
import { actions, selectors } from "@/store";
import MainButton from "@/components/MainButton";
import { useTranslations } from "@/hooks/translations";
import { useNavigate } from "react-router-dom";
import routes from "@/routes";
import { useState } from "react";

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

function BirthtimeCustomAnswer({
  affiliation = "self",
}: IBirthtimeCustomAnswerProps) {
  const { translate } = useTranslations();
  const navigate = useNavigate();
  const dispatch = useDispatch();
  const selfBirthtime = useSelector(selectors.selectBirthtime);
  const questionnaire = useSelector(selectors.selectQuestionnaire);
  const birthtimeFromStore =
    affiliation === "self" ? selfBirthtime : questionnaire.partnerBirthtime;
    
  const [birthtime, setBirthtime] = useState(birthtimeFromStore);

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

  const handleNext = () => {
    if (affiliation === "self") {
      dispatch(actions.questionnaire.update({ birthtime }));
      navigate(`${routes.client.questionnaire()}/profile/birthPlace`);
    }
    if (affiliation === "partner") {
      dispatch(actions.questionnaire.update({ partnerBirthtime: birthtime }));
      navigate(
        `${routes.client.questionnaire()}/partnerProfile/partnerBirthPlace`
      );
    }
  };

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

      <MainButton className={styles.button} onClick={handleNext}>
        {translate("next")}
      </MainButton>
    </div>
  );
}

export default BirthtimeCustomAnswer;
