import React from 'react';
import { useState } from 'react';
import { Link, useNavigate } from 'react-router-dom';
import axios from 'axios';

var API = 'http://localhost:5000/api';

function Register(props) {
  var navigate = useNavigate();
  var formState = useState({ username: '', password: '', confirmPassword: '' });
  var form = formState[0];
  var setForm = formState[1];
  var errorState = useState('');
  var error = errorState[0];
  var setError = errorState[1];

  function submit(e) {
    e.preventDefault();
    setError('');
    if (!form.username || !form.password) {
      setError('All fields are required');
      return;
    }
    if (form.password !== form.confirmPassword) {
      setError('Passwords do not match');
      return;
    }
    if (form.password.length < 4) {
      setError('Password must be at least 4 characters');
      return;
    }
    axios.post(API + '/auth/register', {
      username: form.username,
      password: form.password
    })
      .then(function(res) {
        props.onLogin(res.data);
        navigate('/dashboard');
      })
      .catch(function(err) {
        var msg = 'Registration failed';
        if (err.response && err.response.data && err.response.data.message) {
          msg = err.response.data.message;
        }
        setError(msg);
      });
  }

  return (
    <main className="auth-page">
      <section className="auth-card">
        <h1>Create Account</h1>
        <form onSubmit={submit} className="auth-form">
          {error && <p className="form-error">{error}</p>}
          <input
            placeholder="Username"
            value={form.username}
            onChange={function(e) { setForm({ username: e.target.value, password: form.password, confirmPassword: form.confirmPassword }); }}
          />
          <input
            type="password"
            placeholder="Password"
            value={form.password}
            onChange={function(e) { setForm({ username: form.username, password: e.target.value, confirmPassword: form.confirmPassword }); }}
          />
          <input
            type="password"
            placeholder="Confirm Password"
            value={form.confirmPassword}
            onChange={function(e) { setForm({ username: form.username, password: form.password, confirmPassword: e.target.value }); }}
          />
          <button type="submit">Register</button>
          <div className="auth-links">
            <Link to="/login">Back to Login</Link>
          </div>
        </form>
      </section>
    </main>
  );
}

export default Register;
