import React, { useEffect, useState } from 'react';
import Logo from '../components/Logo'
import styles from "./Page.module.css";
import {useAuth} from "../contexts/AuthContext";
import { useNavigate } from "react-router-dom";
import Button from "../components/Button";

export default function Register() {
  const [name, setName] = useState("");
  const [username, setUsername] = useState("");
  const [password, setPassword] = useState("");
  const [passwordConfirmation, setPasswordConfirmation] = useState("");
  const [showError, setShowError] = useState(false);
  const [errorMessage, setErrorMessage] = useState("");

  const { login, register, isAuthenticated, isRegistratonEnabled } = useAuth();
  const navigate = useNavigate();

  async function handleSubmit(e) {
    e.preventDefault();
    if (!username || !name  || !password || !passwordConfirmation) {
      setErrorMessage("Some required fields are empty.");
      setShowError(true);
      return;
    } else if (password !== passwordConfirmation){
      setErrorMessage("Passwords don't match");
      setShowError(true);
      return;
    }

  

    try {
      setShowError(false); 
      await register(name, username, password);
      await login(username, password);
    } catch (err) {
      setErrorMessage("Registration failed");
      setShowError(true);
    }
  }

  useEffect(() => {
    if (isAuthenticated) {
      navigate("/app");
    }
    if (isRegistratonEnabled == false) {
      navigate("/");
    }
  }, [isRegistratonEnabled, isAuthenticated, navigate]);
  return (
    <main className={styles.page}>
      <form className={styles.form} onSubmit={handleSubmit}>
        <div className={styles.row}>
          <Logo className={styles.logo} />
        </div>

        {showError && (
          <div className={styles.row}>
            <div className={styles.error}>
              <h1>{errorMessage}</h1>
            </div>
          </div>
        )}

        <div className={styles.row}>
          <label htmlFor="name">Display name</label>
          <input
            id="name"
            onChange={(e) => setName(e.target.value)}
            value={name}
          />
        </div>

        <div className={styles.row}>
          <label htmlFor="username">Username</label>
          <input
            id="username"
            onChange={(e) => setUsername(e.target.value)}
            value={username}
          />
        </div>

        <div className={styles.row}>
          <label htmlFor="password">Password</label>
          <input
            type="password"
            id="password"
            onChange={(e) => setPassword(e.target.value)}
            value={password}
          />
        </div>
        <div className={styles.row}>
          <label htmlFor="passwordConfirmation">Password confirmation</label>
          <input
            type="password"
            id="passwordConfirmation"
            onChange={(e) => setPasswordConfirmation(e.target.value)}
            value={passwordConfirmation}
          />
        </div>

        <div className={styles.btnrow}>
          <Button type="primary">Register & login</Button>
          <a className={styles.secondbtn} href="/">Back</a>
        </div>
      </form>

    </main>
  );
}
