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 Login(props) {
  var navigate = useNavigate();
  var formState = useState({ username: '', password: '' });
  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;
    }
    axios.post(API + '/auth/login', form)
      .then(function(res) {
        props.onLogin(res.data);
        navigate('/dashboard');
      })
      .catch(function(err) {
        var msg = 'Login 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>SRMS Login</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 }); }}
          />
          <input
            type="password"
            placeholder="Password"
            value={form.password}
            onChange={function(e) { setForm({ username: form.username, password: e.target.value }); }}
          />
          <button type="submit">Login</button>
          <div className="auth-links">
            <Link to="/register">Create Account</Link>
          </div>
        </form>
      </section>
    </main>
  );
}

export default Login;
