"use client";

import "./SignInForm.scss";
import { useEffect, useState } from "react";
import InputWithLabel from "@/Entities/InputWithLabel/InputWithLabel";
import Button from "@/Shared/UI/Button/Button";
import { useRouter } from "next/navigation";
import CustomLink from "@/Entities/CustomLink/CustomLink";
import GoogleButton from "@/Entities/GoogleButton/GoogleButton";
import { useSignIn } from "./sign-in.store";
import DefaultLoader from "@/Shared/UI/DefaultLoader/DefaultLoader";
import { signIn } from "next-auth/react";

const SignInForm = () => {
  const [email, setEmail] = useState<string>("");
  const [password, setPassword] = useState<string>("");

  const router = useRouter();

  const handleSubmit: React.FormEventHandler<
    HTMLFormElement
  > = async (e) => {
    e.preventDefault();

    const formData = new FormData(e.currentTarget);

    console.log(formData.get("email"), formData.get("email"));

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

    if (res && !res.error) {
      router.push("/profile");
    } else {
      console.log(res?.error);
    }
  };

  return (
    <form className="sign-in-form" onSubmit={handleSubmit}>
      <div className="sign-in-form__inputs">
        <InputWithLabel
          name="email"
          label="Email"
          value={email}
          onChange={(e) => setEmail(e.target.value)}
          placeholder="Введите email"
          error=""
        />
        <InputWithLabel
          name="password"
          label="Пароль"
          value={password}
          onChange={(e) => setPassword(e.target.value)}
          placeholder="Введите пароль"
          secret
          error=""
        />
      </div>

      <CustomLink
        path="/forgot-password"
        style={{ justifySelf: "flex-end" }}
      >
        Забыли пароль?
      </CustomLink>

      <div className="sign-in-form__btns">
        <Button type="submit">Войти</Button>
        <GoogleButton>Войти через Google</GoogleButton>
      </div>

      <div className="sign-in-form__no-account">
        <span>Еще нет аккаунта?</span>

        <CustomLink path="/sign-up">Зарегистрируйтесь</CustomLink>
      </div>
    </form>
  );
};

export default SignInForm;
