"use client";

import AuthInput from "@/features/AuthInput/AuthInput";
import "./ResetCodeForm.scss";
import { useState } from "react";
import { apiInstance } from "@/shared/config/apiConfig";
import { ITokens } from "@/shared/types/token-type";
import Loader from "@/shared/ui/components/Loader/Loader";
import { useRouter } from "@/shared/config/navigation";
import { AxiosError } from "axios";

const ResetCodeForm = () => {
  const [passwordWarning, setPasswordWarning] = useState<string>("");
  const [passwordConfirmWarning, setPasswordConfirmWarning] =
    useState<string>("");
  const [error, setError] = useState<string>("");
  const [loader, setLoader] = useState<boolean>(false);
  const router = useRouter();

  const handleSubmit: React.MouseEventHandler<
    HTMLFormElement
  > = async (e) => {
    e.preventDefault();
    const formData = new FormData(e.currentTarget);

    if (!formData.get("new_password1")) {
      setError("");
      setPasswordConfirmWarning("");
      setPasswordWarning("Заполните поле с новым паролем");
      return;
    }

    if (!formData.get("new_password1")) {
      setError("");
      setPasswordWarning("");
      setPasswordConfirmWarning(
        "Заполните поле с новым паролем потверждения"
      );
      return;
    }

    try {
      setError("");
      setPasswordWarning("");
      setPasswordConfirmWarning("");
      setLoader(true);

      const storage = localStorage.getItem("transitional");
      if (storage === null) return;
      const transitional: ITokens = JSON.parse(storage);

      const Authorization = `Bearer ${transitional.access_token}`;

      const config = {
        headers: {
          Authorization,
        },
      };

      const response = await apiInstance.put(
        "/users/password_reset/confirm/",
        formData,
        config
      );

      if ([200, 201].includes(response.status)) {
        localStorage.removeItem("transitional");
        router.push("/sign-in");
      }
    } catch (error) {
      if (error instanceof AxiosError) {
        if (
          [500, 501, 502, 503, 504].includes(
            error.response?.status as number
          )
        ) {
          setError("Ошибка на стороне сервера");
        } else if (
          [400, 404].includes(error.response?.status as number)
        ) {
          setError(
            "Слабый пароль, прошу избегайте очевидных паролей"
          );
        }
      } else {
        setError("Произошла непредвиденная ошибка");
      }
    } finally {
      setLoader(false);
    }
  };

  return (
    <form onSubmit={handleSubmit} className="reset-code-form">
      <div className="reset-code-form__inputs">
        <AuthInput
          name="new_password1"
          label="Введите пароль"
          error={passwordWarning}
          isPassword
          placeholder="Введите новый пароль"
        />
        <AuthInput
          name="new_password2"
          label="Повторите пароль"
          error={passwordConfirmWarning}
          isPassword
          placeholder="Потвердите новый пароль"
        />
      </div>

      {error ? (
        <p className="reset-code-form__error">{error}</p>
      ) : null}
      <button className="reset-code-form__btn" type="submit">
        {loader ? <Loader /> : "Сохранить"}
      </button>
    </form>
  );
};

export default ResetCodeForm;
