import React, { useState, useEffect } from "react";
import "../../components/StylizedBtn/StylizedBtn.scss";
import { useAuth } from "../../hooks";
import passwordCheck from "../../services/password";

export const Register = () => {
  const { register } = useAuth();
  const [username, setUsername] = useState("");
  const [password, setPassword] = useState("");
  const [confirmation, setConfirmation] = useState("");

  useEffect(() => {
    document.title = "Inscription";
  }, []);

  const onSubmit = async (e) => {
    try {
      e.preventDefault();
      if (!passwordCheck(password, confirmation)) {
        alert(
          "Assurez vous que le mot de passe contient au moins 8 caracteres dont une majuscule, un symbole special et au minimum un chiffre.",
        );
        return;
      }
      await register(username, password, confirmation);
    } catch (err) {
      console.error(err);
    }
  };

  return (
    <div className="container">
      <form className="form" onSubmit={onSubmit}>
        <h3 className="title">Inscription</h3>

        <input
          type="text"
          value={username}
          placeholder="Pseudo"
          className="ipt"
          required
          onChange={(e) => setUsername(e.target.value)}
        />
        <input
          type="password"
          className="ipt"
          value={password}
          required
          min={8}
          placeholder="Mot de passe"
          onChange={(e) => setPassword(e.target.value)}
        />
        <input
          type="password"
          className="ipt"
          min={8}
          required
          value={confirmation}
          placeholder="Confirmation du mot de passe"
          onChange={(e) => setConfirmation(e.target.value)}
        />
        <button className="stylized-btn" type="submit">
          Go
        </button>
      </form>
    </div>
  );
};
