// Login page. Port of the Angular LoginComponent.
//
// The original component called authenticationService.login() (which
// subscribed internally and returned void) and then polled with a
// 3-second setTimeout hoping the token had arrived. Because
// AuthContext.login() is a Promise that resolves only after the token
// is stored, this version simply awaits it and navigates — the race
// condition and the timer are gone, and failed logins surface a real
// error message instead of a console.log.
import { FormEvent, useState } from 'react';
import { useNavigate } from 'react-router-dom';
import { useAuth } from '../context/AuthContext';

export default function Login() {
  const [name, setName] = useState('');
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');
  const [formError, setFormError] = useState('');
  const { login } = useAuth();
  const navigate = useNavigate();

  const handleSubmit = async (event: FormEvent) => {
    event.preventDefault();
    setFormError('');

    if (!email || !password || !name) {
      setFormError('All fields are required, please try again');
      return;
    }

    try {
      await login({ name, email }, password);
      navigate('/');
    } catch {
      setFormError('Login failed. Please check your credentials.');
    }
  };

  return (
    <div className="row">
      <div className="col-12 col-md-8">
        <h2>Login</h2>
        <form onSubmit={handleSubmit} noValidate>
          {formError && (
            <div role="alert" className="alert alert-danger">
              {formError}
            </div>
          )}
          <div className="form-group">
            <label htmlFor="name">Name</label>
            <input
              id="name"
              type="text"
              placeholder="Enter Name"
              value={name}
              onChange={(event) => setName(event.target.value)}
            />
          </div>
          <div className="form-group">
            <label htmlFor="email">Email Address</label>
            <input
              id="email"
              type="email"
              placeholder="Enter email address"
              value={email}
              onChange={(event) => setEmail(event.target.value)}
            />
          </div>
          <div className="form-group">
            <label htmlFor="password">Password</label>
            <input
              id="password"
              type="password"
              className="form-control"
              placeholder="e.g 12+ alphanumerics"
              value={password}
              onChange={(event) => setPassword(event.target.value)}
            />
          </div>
          <button type="submit" className="btn btn-primary">
            Sign In!
          </button>
        </form>
      </div>
    </div>
  );
}
