import { FormEvent, useState } from 'react';

import { useAuth } from '../../state/AuthContext';

export function LoginForm(): JSX.Element {
  const { login, register, logout, status, error } = useAuth();
  const [mode, setMode] = useState<'login' | 'register'>('login');
  const [username, setUsername] = useState('demo');
  const [password, setPassword] = useState('railgame123');
  const [fullName, setFullName] = useState('');

  const isSubmitting = status === 'authenticating';
  const isRegisterMode = mode === 'register';

  async function handleSubmit(event: FormEvent<HTMLFormElement>) {
    event.preventDefault();
    if (isRegisterMode) {
      await register(username, password, fullName || undefined);
    } else {
      await login(username, password);
    }
  }

  function toggleMode() {
    setMode((current) => (current === 'login' ? 'register' : 'login'));
    setUsername('');
    setPassword('');
    setFullName('');
    logout();
  }

  return (
    <form className="auth-card" onSubmit={handleSubmit}>
      <div className="auth-card__heading">
        <h2>{isRegisterMode ? 'Create an account' : 'Sign in'}</h2>
        <button
          type="button"
          className="link-button"
          onClick={toggleMode}
          disabled={isSubmitting}
        >
          {isRegisterMode ? 'Have an account? Sign in' : 'Need an account? Register'}
        </button>
      </div>

      <p className="auth-helper">
        {isRegisterMode
          ? 'Choose a username and password to create a new profile.'
          : 'Use the demo credentials to explore the prototype.'}
      </p>

      {isRegisterMode && (
        <>
          <label htmlFor="fullName">Full name</label>
          <input
            id="fullName"
            autoComplete="name"
            value={fullName}
            onChange={(event) => setFullName(event.target.value)}
            disabled={isSubmitting}
          />
        </>
      )}

      <label htmlFor="username">Username</label>
      <input
        id="username"
        autoComplete="username"
        value={username}
        onChange={(event) => setUsername(event.target.value)}
        disabled={isSubmitting}
        required
      />

      <label htmlFor="password">Password</label>
      <input
        id="password"
        type="password"
        autoComplete={isRegisterMode ? 'new-password' : 'current-password'}
        value={password}
        onChange={(event) => setPassword(event.target.value)}
        disabled={isSubmitting}
        required
      />

      {error && <p className="error-text">{error}</p>}
      <button type="submit" disabled={isSubmitting}>
        {isSubmitting
          ? isRegisterMode
            ? 'Creating account…'
            : 'Signing in…'
          : isRegisterMode
            ? 'Register'
            : 'Sign in'}
      </button>
    </form>
  );
}
