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

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

function BirthdateCustomAnswer({
  affiliation = "self",
}: IBirthdateCustomAnswerProps) {
  const { translate } = useTranslations();
  const navigate = useNavigate();
  const dispatch = useDispatch();
  const selfBirthdate = useSelector(selectors.selectBirthdate);
  const questionnaire = useSelector(selectors.selectQuestionnaire);
  const birthdateFromStore =
    affiliation === "self" ? selfBirthdate : questionnaire.partnerBirthdate;

  const [birthdate, setBirthdate] = useState(birthdateFromStore);
  const [isDisabled, setIsDisabled] = useState(true);
  const handleValid = (_birthdate: string) => {
    if (affiliation === "self") {
      dispatch(actions.form.addDate(birthdate));
    }
    setBirthdate(_birthdate);
    setIsDisabled(_birthdate === "");
  };

  const handleNext = () => {
    if (affiliation === "self") {
      dispatch(actions.questionnaire.update({ birthdate }));
      navigate(routes.client.singleZodiacInfo());
    }
    if (affiliation === "partner") {
      dispatch(actions.questionnaire.update({ partnerBirthdate: birthdate }));
      navigate(routes.client.relationshipZodiacInfo());
    }
  };

  return (
    <div className={styles.container}>
      <DatePicker
        name="birthdate"
        value={birthdate}
        onValid={handleValid}
        onInvalid={() => setIsDisabled(true)}
        inputClassName="date-picker-input"
      />

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

export default BirthdateCustomAnswer;
