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 [loginAttempts, setLoginAttempts] = useState(0);

  const [captcha, setCaptcha] = useState("");
  const [showCaptcha, setShowCaptcha] = useState(false);

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

    try {

      if(showCaptcha && captcha.toLowerCase() !== "laudenbach") {
        setError("Captcha falsch. Bitte versuche es erneut.");
        return;
      }

      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.");
        const newAttempts = loginAttempts + 1;
        setLoginAttempts(newAttempts);

        if(newAttempts >= 3) {
          setShowCaptcha(true);
        }
      }
    }
    
  };

  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
            />
            {showCaptcha && (
              <div>
                <label className="text-sm text-gray-700">Was ist der beste Verein?</label>
                <Input
                  placeholder="Antwort (z. B. Laudenbach)"
                  value={captcha}
                  onChange={(e) => setCaptcha(e.target.value)}
                  required
                />
              </div>
            )}
            {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;
