import styles from "./styles.module.scss";
import { useNavigate } from "react-router-dom";
import { useUpdateStep } from "@/components/ChatsPath/hooks/useUpdateStep";
import routes from "@/routes";
import Button from "@/components/ChatsPath/ui/Button";
import { useDispatch, useSelector } from "react-redux";
import { actions, selectors } from "@/store";
import Tip from "@/components/ChatsPath/components/Tip";
import NameInput from "@/components/pages/ABDesign/v1/pages/EmailEnterPage/NameInput";
import { useState } from "react";
import { ESourceAuthorization } from "@/api/resources/User";
import { useSession } from "@/hooks/session/useSession";
import { useTranslations } from "@/hooks/translations";
import { ELocalesPlacement } from "@/locales";

function UserName() {
  const { translate } = useTranslations(ELocalesPlacement.Chats);
  const { updateSession } = useSession();
  useUpdateStep(29);
  const navigate = useNavigate();
  const dispatch = useDispatch();
  const answer = useSelector(selectors.selectAnswers)?.userName;
  const [name, setName] = useState("");
  const [isValidName, setIsValidName] = useState(false);

  const handleNext = async () => {
    if (!answer?.length) return;
    await updateSession(
      {
        profile: {
          name,
        },
      },
      ESourceAuthorization["aura.chats"]
    );
    navigate(routes.client.chatsQuizProcessing());
  };

  const handleValidName = (name: string) => {
    if (name) {
      dispatch(
        actions.user.update({
          username: name,
        })
      );
      dispatch(actions.chats.updateAnswers({ userName: name }));
    }
    setName(name);
    setIsValidName(true);
  };

  const handleInvalidName = () => {
    dispatch(
      actions.user.update({
        username: "",
      })
    );
    dispatch(actions.chats.updateAnswers({ userName: "" }));
    setName("");
    setIsValidName(false);
  };

  return (
    <>
      <h2 className={`chats-answers-title ${styles.title}`}>
        {translate("/quiz/userName.title")}
      </h2>
      <Tip icon="🙌" text={translate("/quiz/userName.description")} />
      <NameInput
        value={name}
        placeholder={translate("/quiz/userName.placeholder")}
        onValid={handleValidName}
        onInvalid={handleInvalidName}
        inputClassName={styles["input-name"]}
      />
      <Button
        disabled={!isValidName}
        classNameContainer={styles.button}
        onClick={handleNext}
      >
        {translate("/quiz/userName.finish")}
      </Button>
    </>
  );
}

export default UserName;
