"use client";

import { useState } from "react";

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

  async function handleLogin(e: React.FormEvent) {
    e.preventDefault();

    setError("");

    try {
      const response = await fetch("/api/login", {
        method: "POST",
        headers: {
          "Content-Type": "application/json",
        },
        body: JSON.stringify({
          username,
          password,
        }),
      });

      const data = await response.json();

      if (response.ok) {
        window.location.href = "/dashboard";
        return;
      }

      setError(data.detail ?? "Login fehlgeschlagen");
    } catch (err) {
      console.error(err);
      setError("Technischer Fehler");
    }
  }

  return (
    <main className="flex min-h-screen items-center justify-center bg-slate-100">
      <form
        onSubmit={handleLogin}
        className="w-full max-w-md rounded-xl bg-white p-8 shadow-xl"
      >
        <h1 className="mb-8 text-center text-3xl font-bold">
          Olympus CRM
        </h1>

        <input
          className="mb-4 w-full rounded border p-3"
          placeholder="Benutzername"
          value={username}
          onChange={(e) => setUsername(e.target.value)}
        />

        <input
          className="mb-4 w-full rounded border p-3"
          type="password"
          placeholder="Passwort"
          value={password}
          onChange={(e) => setPassword(e.target.value)}
        />

        {error && (
          <p className="mb-4 text-red-600">{error}</p>
        )}

        <button
          type="submit"
          className="w-full rounded bg-blue-600 p-3 text-white hover:bg-blue-700"
        >
          Anmelden
        </button>
      </form>
    </main>
  );
}
