'use client';
import { useState } from 'react';
import axios from 'axios';
import Cookies from 'js-cookie';

export default function Login() {
  const [email, setEmail] = useState('');
  const [password, setPassword] = useState('');

  const handleLogin = async (e: React.FormEvent) => {
    e.preventDefault();
    
    try {
        const response = await fetch('http://localhost:2006/auth/login', {
        method: 'POST',
        headers: {
          'Content-Type': 'application/json',
        },
        body: JSON.stringify({
          email,
          password,
        }),
      });

      if (response.ok) {
        const data= await response.json();
        console.log('Login successful:', data.token);
        // Speichere das JWT im Cookie
        Cookies.set('token', data.token);
        
    }else{
        console.error('Login failed:', response.statusText);
    }
      // Weiterleitung zur geschützten Route
    } catch (error) {
      console.error('Login error:', error);
      alert(JSON.stringify({
          email,
          password,
        }));
      alert(error);
    }
  };

  return (
    <div>
      <h1>Login</h1>
      <form onSubmit={handleLogin}>
        <input 
          type="email"
          value={email}
          onChange={(e) => setEmail(e.target.value)}
          placeholder="E-Mail"
        />
        <input
          type="password"
          value={password}
          onChange={(e) => setPassword(e.target.value)}
          placeholder="Passwort"
        />
        <button type="submit">Login</button>
      </form>
    </div>
  );
}
