import React, { useState } from 'react';
import { api } from '../../api';
import './Login.css';

const Login = ({ onLogin }) => {
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');
  const [username, setUsername] = useState('');
  const [isSignUp, setIsSignUp] = useState(false);
  const [error, setError] = useState('');

  const handleAuth = async (e) => {
    e.preventDefault();
    setError('');

    try {
      let user;
      if (isSignUp) {
        user = await api('/api/auth/register', {
          method: 'POST',
          body: JSON.stringify({ username, email, password }),
        });
      } else {
        user = await api('/api/auth/login', {
          method: 'POST',
          body: JSON.stringify({ email, password }),
        });
      }

      // Save the JWT token and user data for future requests
      localStorage.setItem('token', user.token);
      localStorage.setItem('user', JSON.stringify(user));

      onLogin(user);
    } catch (err) {
      setError(err.message);
    }
  };

  return (
    <div className="login-container">
  <h1 className="login-title">XAVA</h1>

  <form onSubmit={handleAuth} className="login-form">
    <h4>Logge dich ein :)</h4>
    

        {isSignUp && (
          <input
            type="text"
            placeholder="Benutzername"
            value={username}
            onChange={(e) => setUsername(e.target.value)}
            className="login-input"
            required
          />
        )}

        <input
          type="email"
          placeholder="E-Mail"
          value={email}
          onChange={(e) => setEmail(e.target.value)}
          className="login-input"
          required
        />

        <input
          type="password"
          placeholder="Passwort"
          value={password}
          onChange={(e) => setPassword(e.target.value)}
          className="login-input"
          required
        />
        

        {error && <p className="login-error">{error}</p>}

        <button type="submit" className="login-button">
          {isSignUp ? 'Registrieren' : 'Anmelden'}
        </button>

        <button
          type="button"
          className="login-switch"
          onClick={() => setIsSignUp(!isSignUp)}
        >
          {isSignUp ? 'Bereits ein Konto? Anmelden' : 'Kein Konto? Registrieren'}
        </button>
      </form>
    </div>
  );
};

export default Login;
