import Image from "next/image";
import key from "./icons/key.svg";
import AuthInput from "@/features/AuthInput/AuthInput";
import "./confirm-code.scss";
import { useState } from "react";
import { apiInstance } from "@/shared/config/apiConfig";
import Loader from "@/shared/ui/components/Loader/Loader";
import { useRouter } from "next/navigation";
import { ITokens } from "@/shared/types/token-type";

interface IConfirmCodeProps {
  setChangeForm: (boolean: boolean) => void;
}

const ConfirmCode: React.FC<IConfirmCodeProps> = ({
  setChangeForm,
}: IConfirmCodeProps) => {
  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("code")) {
      return setError("Заполните поле");
    }

    try {
      setError("");
      setLoader(true);
      const res = await apiInstance.post<ITokens>(
        "/users/password_reset/code/",
        formData
      );

      if (res.status === 200 || res.status === 201) {
        localStorage.setItem(
          "transitional",
          JSON.stringify(res.data)
        );
        router.push("/sign-in/reset-code");
      }
    } catch (error) {
      setError("An error ocured");
    } finally {
      setLoader(false);
    }
  };
  return (
    <div className="auth-wrapper">
      <div className="auth-icon2">
        <Image src={key} alt="Key Icon" />
      </div>
      <div className="auth-header">
        <h2>Введите код</h2>
        <p>Введите код для сброса и восстановления пароля</p>
      </div>

      <form onSubmit={handleSubmit} className="confirm-code">
        <AuthInput
          type="text"
          name="code"
          label="Код сброса пароля"
          error={error}
          placeholder="Введите код"
        />
        <button type="submit">
          {loader ? <Loader /> : "Сбросить пароль"}
        </button>
      </form>
      <button
        onClick={() => setChangeForm(false)}
        className="confirm-code-send-email"
      >
        Получить код
      </button>
    </div>
  );
};

export default ConfirmCode;
