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 PlacePicker from "@/components/PlacePicker";
import { useState } from "react";

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

function BirthPlaceCustomAnswer({
  affiliation = "self",
}: IBirthPlaceCustomAnswerProps) {
  const { translate } = useTranslations();
  const navigate = useNavigate();
  const dispatch = useDispatch();
  const questionnaire = useSelector(selectors.selectQuestionnaire);
  const birthPlace =
    affiliation === "self"
      ? questionnaire.birthPlace
      : questionnaire.partnerBirthPlace;

  const [isKnownPartnerBirthPlace, setIsKnownPartnerBirthPlace] =
    useState(true);

  const handleChange = (birthPlace: string) => {
    if (affiliation === "partner") {
      return dispatch(
        actions.questionnaire.update({ partnerBirthPlace: birthPlace })
      );
    }
    // affiliation === "self"
    return dispatch(actions.questionnaire.update({ birthPlace }));
  };

  const handleNext = () => {
    if (affiliation === "partner") {
      return navigate(routes.client.relationshipAlmostThere());
    }
    // affiliation === "self"
    return navigate(routes.client.loadingInRelationship());
  };

  return (
    <>
      {affiliation === "partner" && (
        <label className={styles["checkbox-container"]} htmlFor="isKnown">
          <input
            id="isKnown"
            type="checkbox"
            className={styles.checkbox}
            checked={!isKnownPartnerBirthPlace}
            onChange={() => setIsKnownPartnerBirthPlace((prev) => !prev)}
          />
          I don`t know where my partner was born
        </label>
      )}
      <div className={styles.container}>
        <PlacePicker
          value={birthPlace}
          name="birthPlace"
          maxLength={1000}
          isDisabled={!isKnownPartnerBirthPlace}
          onChange={handleChange}
        />

        {(!!birthPlace.length || !isKnownPartnerBirthPlace) && (
          <MainButton className={styles.button} onClick={handleNext}>
            {translate("next")}
          </MainButton>
        )}
      </div>
    </>
  );
}

export default BirthPlaceCustomAnswer;
