"use client";
import { useState } from "react";
import { useRouter } from "next/navigation";
import { apiFetch } from "../../../api";

export default function Page() {
  const router = useRouter();
  const [username, setUsername] = useState("");
  const [password, setPassword] = useState("");
  const [error, setError] = useState("");

  const handleSubmit = async (e: React.FormEvent<HTMLFormElement>) => {
    e.preventDefault(); // verhindert Seitenreload
    setError("");
    try {
      await apiFetch("/auth/login", null, {
        method: "POST",
        body: JSON.stringify({ username, password }),
      });
      // Tokens werden automatisch in HttpOnly Cookies gespeichert
      // Keine localStorage nötig - sicherer!
      router.push("/");
    } catch (e: unknown) {
      const errorMessage = e instanceof Error ? e.message : "Login failed";
      setError(errorMessage);
    }
  };

  return (
    <div className="container">
      <div className="card">
        <img
          src="/logo/doctopus.png"
          alt="Doctopus Logo"
          style={{ width: "300px", marginBottom: "1rem" }}
        />
        <h2>Login</h2>
        <form onSubmit={handleSubmit}>
          <input
            type="text"
            placeholder="Username"
            value={username}
            onChange={(e) => setUsername(e.target.value)}
          />
          <input
            type="password"
            placeholder="Password"
            value={password}
            onChange={(e) => setPassword(e.target.value)}
          />
          <button type="submit">Login</button>
        </form>
        {error && <p className="error">{error}</p>}
      </div>
    </div>
  );
}