"use client";

import "./SignInForm.scss";
import AuthInput from "@/features/AuthInput/AuthInput";
import GoogleButton from "@/features/GoogleButton/GoogleButton";
import { Link, useRouter } from "@/shared/config/navigation";
import Loader from "@/shared/ui/components/Loader/Loader";
import { signIn, useSession } from "next-auth/react";
import { useState } from "react";

const SignInForm = () => {
  const session = useSession();
  const [emailWarning, setEmailWarning] = useState<string>("");
  const [passwordWarning, setPasswordWarning] = 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("email")?.toString()) {
      setError("");
      setPasswordWarning("");
      setEmailWarning("Заполните поле Email");
      return;
    }

    if (!formData.get("password")?.toString()) {
      setError("");
      setEmailWarning("");
      setPasswordWarning("Заполните поле Пароль");
      return;
    }

    setError("");
    setEmailWarning("");
    setPasswordWarning("");
    setLoader(true);

    const res = await signIn("credentials", {
      email: formData.get("email"),
      password: formData.get("password"),
      redirect: false,
    });

    setLoader(false);

    if (res?.ok && !res.error) {
      router.push("/profile/personal");
    } else if ([400, 401, 404].includes(res?.status as number)) {
      setError("Неверный Email или Пароль");
    } else {
      setError("Произошла непредвиденная ошибка");
    }
  };

  return (
    <form className="sign-in-form" onSubmit={handleSubmit}>
      <div className="sign-in-form__inputs">
        <AuthInput
          type="email"
          label="Email"
          placeholder="Введите email"
          error={emailWarning}
          name="email"
        />
        <AuthInput
          isPassword
          label="Пароль"
          placeholder="Введите пароль"
          error={passwordWarning}
          name="password"
        />
      </div>
      {error ? <p className="sign-in-form__error">{error}</p> : null}
      <Link
        href="/sign-in/forgot-password"
        className="sign-in-form__forgot-password"
      >
        Забыли пароль?
      </Link>

      <div className="sign-in-form__btns">
        <button className="sign-in-form__btns_first" type="submit">
          {loader ? <Loader /> : "Войти"}
        </button>

        <GoogleButton />
      </div>
    </form>
  );
};

export default SignInForm;
