import { useState } from "react";
import { useNavigate } from "react-router-dom";
import { Input } from "@/components/ui/input";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";

const apiBase = import.meta.env.VITE_API_URL;

const LoginPage = () => {
  const [email, setEmail] = useState(""); // Wird eigentlich Username sein!
  const [password, setPassword] = useState("");
  const [error, setError] = useState("");
  const navigate = useNavigate();

  const handleLogin = async (e: React.FormEvent) => {
    e.preventDefault();
    setError("");

    try {
      const res = await fetch(`${apiBase}/api/login`, {
        method: "POST",
        headers: { "Content-Type": "application/json" },
        body: JSON.stringify({ username: email, password }),
      });
    
      if (!res.ok) {
        if (res.status === 429) {
          throw new Error("rate_limit");
        }
        throw new Error("login_failed");
      }
    
      const data = await res.json();
      localStorage.setItem("token", data.token);
      navigate("/admin");
    } catch (err: any) {
      console.error(err);
      if (err.message === "rate_limit") {
        setError("Zu viele fehlgeschlagene Login-Versuche. Bitte versuch es später erneut.");
      } else {
        setError("Login fehlgeschlagen. Bitte prüfe Benutzername und Passwort.");
      }
    }
    
  };

  return (
    <div className="flex justify-center items-center min-h-screen bg-gray-50">
      <Card className="w-full max-w-md">
        <CardHeader>
          <CardTitle className="text-center text-frog-600">Login</CardTitle>
        </CardHeader>
        <CardContent>
          <form className="space-y-4" onSubmit={handleLogin}>
            <Input
              placeholder="Benutzername"
              type="text"
              value={email}
              onChange={(e) => setEmail(e.target.value)}
              required
            />
            <Input
              placeholder="Passwort"
              type="password"
              value={password}
              onChange={(e) => setPassword(e.target.value)}
              required
            />
            {error && <p className="text-red-500 text-sm">{error}</p>}
            <Button type="submit" className="w-full bg-frog-500 hover:bg-frog-600 text-white">
              Einloggen
            </Button>
          </form>
        </CardContent>
      </Card>
    </div>
  );
};

export default LoginPage;
