import { useState } from 'react';
import { useAuth } from './AuthContext';
import { login as apiLogin } from './api';
// import { jwtDecode } from 'jwt-decode';
import { useNavigate } from 'react-router-dom';
import { getUserFromToken } from '../components/utils/jwt';
export default function LoginPage() {
  const { login } = useAuth();
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');
  const [error, setError] = useState<string | null>(null);
  const navigate = useNavigate(); // ← Navigation-Hook


  async function handleSubmit(e: React.FormEvent) {
    e.preventDefault();
    try {
      const data = await apiLogin(email, password);
      // Token aus JWT extrahieren (hier: UserID im Token Payload)
      // Für Demo: Einfach Dummy UserID setzen, oder später JWT decode implementieren
      
      var decodedData = getUserFromToken(data.token);
      if (!decodedData || !decodedData.userId || !decodedData.role) {
        setError('Ungültiges Token');
        return;
      } 
      // Dummy UserID für Demo                    
      login(data.token, decodedData.userId, decodedData.role);
      // Nach dem Login zur Dashboard-Seite navigieren
      setTimeout(() => {
          navigate('/');
      }, 1000);   
     } catch {
      setError('Login fehlgeschlagen');
    }
  }

  return (
    <form onSubmit={handleSubmit} className="max-w-md mx-auto p-6">
      <h2 className="text-2xl mb-4">Login</h2>
      {error && <p className="text-red-600 mb-4">{error}</p>}
      <input type="email" placeholder="E-Mail" required value={email} onChange={e => setEmail(e.target.value)} className="border p-2 w-full mb-4" />
      <input type="password" placeholder="Passwort" required value={password} onChange={e => setPassword(e.target.value)} className="border p-2 w-full mb-4" />
      <button type="submit" className="bg-blue-600 text-white p-2 rounded w-full">Einloggen</button>
    </form>
  );
}
