import React from "react";
import "../Auth.css";
import { useTranslation } from "react-i18next";
import { Link, useNavigate } from "react-router-dom";
import AuthHeader from "../AuthHeader";
import CInput from "../../../components/CInput";
import CButton from "../../../components/CButton";
import { useForm } from "react-hook-form";
import { useSelector } from "react-redux";
import { useAppDispatch, type RootState } from "../../../stores/store";
import { authRegister } from "../../../stores/slices/authSlice";
import { TG_USER_ID } from "../../../constants/constants";
import { useAuth } from "../../../contexts/AuthContext/useAuth";
import TheCybernanny from "../../../assets/images/TheCybernanny.png";

interface IRegisterFormData {
  login: string;
  password: string;
  termsAccepted: boolean;
  privacyAccepted: boolean;
}

const Register: React.FC = () => {
  const { t } = useTranslation();
  const { setAuthenticated } = useAuth();
  const navigate = useNavigate();

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

  const dispatch = useAppDispatch();
  const { loadingRegister, errorRegister } = useSelector(
    (state: RootState) => state.auth
  );

  const onSubmit = async (data: IRegisterFormData) => {
    try {
      const result = await dispatch(authRegister(data));

      if (authRegister.fulfilled.match(result)) {
        const token = result.payload.token;
        localStorage.setItem(`token-${TG_USER_ID}`, token);
        setAuthenticated(true);
        navigate("/home");
      }
    } catch (e) {
      console.error("Unexpected error in login form", e);
    }
  };

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

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

      <h2>{t("auth.register")}</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("password", {
            required: t("error.requiredField"),
            minLength: {
              value: 6,
              message: t("error.passwordMinLength"),
            },
          })}
          error={errors.password?.message as string}
        />

        <div>
          <div className="auth__agreement">
            <input
              type="checkbox"
              id="terms"
              {...register("termsAccepted", {
                required: t("error.requiredCheckbox") || "Required",
              })}
            />
            <label htmlFor="terms">
              <span>{t("auth.iaccept")} </span>
              <Link to="/auth/terms">{t("auth.terms")}</Link>
            </label>
          </div>

          {errors.termsAccepted && (
            <p className="auth__form__text__danger">
              {errors.termsAccepted.message}
            </p>
          )}
        </div>

        <div>
          <div className="auth__agreement">
            <input
              type="checkbox"
              id="privacy"
              {...register("privacyAccepted", {
                required: t("error.requiredCheckbox") || "Required",
              })}
            />
            <label htmlFor="privacy">
              <span>{t("auth.iaccept")} </span>
              <Link to="/auth/privacy">{t("auth.privacyPolicy")}</Link>
            </label>
          </div>

          {errors.privacyAccepted && (
            <p className="auth__form__text__danger">
              {errors.privacyAccepted.message}
            </p>
          )}
        </div>

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

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

export default Register;
