import shortlinkLogo from '../assets/trx-shortlink-orange.png'
import '../App.css'
import { useState } from "react";


function Login() {
  
  const [username, setUsername] = useState("");
  const [password, setPassword] = useState("");
  const [error, setError] = useState("");
  
  const handleLogin = async () => {
    try {
      const res = await fetch("http://localhost:3000/api/login", {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({
    username: (document.getElementById("username")as HTMLInputElement).value,
    password: (document.getElementById("password")as HTMLInputElement).value
  }),
        credentials: "include", // wichtig für Cookies (Session)
      });

      const data = await res.json();
      if (res.ok) {
        //  Login erfolgreich
        console.log("Eingeloggt!");
        location.href = "/admin"
      } else {
        setError(data.message || "Login fehlgeschlagen");
      }
    } catch (err) {
      setError("Serverfehler beim Login \n\n\n" + err);
      
    }
  };

  return (
    <>
      <header>
      <div className="nav">
        <nav id="main-nav">
        <ul id="centerlist">
          <li id="home"> <a draggable="false" href="home">Home</a> </li>
          
          
        </ul>
        <ul id="rightlist">
          <li id="login"> <a draggable="false" href="login">Login</a></li>
        </ul>
      </nav>
      </div>
      </header>
      <div id="logoname">
        <a href="/home" >
          <img src={shortlinkLogo} draggable="false" className="logo" alt="trx shortlink logo" />
        </a>
        <h1>trx shortlink</h1>
      </div>
      <div className="card">
        <h2>Login</h2>
      <input
        className="login"
        id="username"
        placeholder="Username"
        value={username}
        onChange={(e) => setUsername(e.target.value)}
      /><br />
      <input
        className="login"
        id="password"
        type="password"
        placeholder="Password"
        value={password}
        onChange={(e) => setPassword(e.target.value)}
      /><br />
      <button id="login" onClick={handleLogin}>Login</button>
      {error && <p style={{ color: "red" }}>{error}</p>}
      </div>
    </>
  )
}


export default Login;
