"use client";

import { useEffect, useState } from "react";
import "./SignUpForm.scss";
import InputWithLabel from "@/Entities/InputWithLabel/InputWithLabel";
import Button from "@/Shared/UI/Button/Button";
import CustomLink from "@/Entities/CustomLink/CustomLink";
import { useRouter } from "next/navigation";
import GoogleButton from "@/Entities/GoogleButton/GoogleButton";
import { useSignUp } from "./sign-up.store";
import DefaultLoader from "@/Shared/UI/DefaultLoader/DefaultLoader";

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

  const router = useRouter();

  const {
    redirect,
    register,
    loading,
    emailError,
    passwordError,
    confirmPasswordError,
    matchPasswordError,
    error,
  } = useSignUp();

  useEffect(() => {
    if (redirect) {
      router.push("/confirm-email");
    }
  }, [redirect]);

  return (
    <form
      className="sign-up-form"
      onSubmit={(e) => {
        e.preventDefault();
        register(email, password, confirmPassword);
      }}
    >
      <div className="sign-up-form__inputs">
        <InputWithLabel
          label="Email"
          placeholder="Введите email"
          value={email}
          onChange={(e) => setEmail(e.target.value)}
          error={emailError}
        />
        <InputWithLabel
          label="Пароль"
          placeholder="Введите пароль"
          value={password}
          onChange={(e) => setPassword(e.target.value)}
          secret
          error={passwordError}
        />
        <InputWithLabel
          label="Пароль Потверждения"
          placeholder="Повторите пароль"
          value={confirmPassword}
          onChange={(e) => setConfirmPassword(e.target.value)}
          secret
          error={confirmPasswordError}
        />
        {matchPasswordError ? <p>{matchPasswordError}</p> : null}
        {error ? <p>{error}</p> : null}
      </div>
      <div className="sign-up-form__btns">
        <Button
          type="submit"
          onClick={() => router.push("/confirm-email")}
        >
          {loading ? <DefaultLoader /> : "Зарегистрироваться"}
        </Button>
        <GoogleButton>Войти через Google</GoogleButton>
      </div>

      <div className="sign-up-form__has-account">
        <span>Уже есть аккаунт?</span>
        <CustomLink path="/sign-in">Войти в аккаунт</CustomLink>
      </div>
    </form>
  );
};

export default SignUpForm;
