import React from "react";
import "../Auth.css";
import AuthHeader from "../AuthHeader";
import { useNavigate } from "react-router-dom";
import { useTranslation } from "react-i18next";
import CInput from "../../../components/CInput";
import CButton from "../../../components/CButton";
import { useForm } from "react-hook-form";
import {
  useAppDispatch,
  useAppSelector,
  type RootState,
} from "../../../stores/store";
import { authRecover } from "../../../stores/slices/authSlice";
import TheCybernanny from "../../../assets/images/TheCybernanny.png";

interface IRecoverFormData {
  login: string;
  newPassword: string;
  repeatPassword: string;
}

const Recover: React.FC = () => {
  const { t } = useTranslation();
  const navigate = useNavigate();
  const dispatch = useAppDispatch();
  const { loadingRecover, errorRecover, successRecover } = useAppSelector(
    (state: RootState) => state.auth
  );

  const {
    register,
    handleSubmit,
    formState: { errors },
    watch,
  } = useForm<IRecoverFormData>();

  const newPasswordValue = watch("newPassword");

  const onSubmit = async (data: IRecoverFormData) => {
    dispatch(authRecover(data));
  };

  return (
    <div className="wrapper recover">
      <AuthHeader back onBack={() => navigate("/")} />

      <div className="auth__logo">
        <img src={TheCybernanny} alt="TheCybernanny" />
      </div>

      <h2>{t("auth.passwordRecovery")}</h2>

      <form className="auth__form" onSubmit={handleSubmit(onSubmit)}>
        <CInput
          label={`${t("auth.login")}`}
          placeholder={`${t("auth.loginPlaceholder")}`}
          {...register("login", { required: t("error.requiredField") })}
          error={errors.login?.message as string}
        />

        <CInput
          label={`${t("auth.newPassword")}`}
          placeholder={`${t("auth.newPasswordPlaceholder")}`}
          type="password"
          {...register("newPassword", {
            required: t("error.requiredField"),
            minLength: {
              value: 6,
              message: t("error.passwordMinLength"),
            },
          })}
          error={errors.newPassword?.message as string}
        />

        <CInput
          label={`${t("auth.repeatPassword")}`}
          placeholder={`${t("auth.repeatPasswordPlaceholder")}`}
          type="password"
          {...register("repeatPassword", {
            required: t("error.requiredField"),
            validate: (value) =>
              value === newPasswordValue || t("auth.passwordsDoNotMatch"),
          })}
          error={errors.repeatPassword?.message as string}
        />

        {successRecover && (
          <p className="text-success text-center">{successRecover}</p>
        )}
        {errorRecover && (
          <p className="text-danger text-center">{errorRecover}</p>
        )}

        <CButton title={`${t("button.continue")}`} isLoading={loadingRecover} />
      </form>
    </div>
  );
};

export default Recover;
