"use client";

import { useState, useEffect } from "react";
import { useRouter } from "next/navigation";
import { login } from "@/lib/api";
import { getCachedUser, setCachedUser, clearAuthCache } from "@/lib/auth-cache";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Label } from "@/components/ui/label";

const ADMIN_ROLES = ["auditor", "admin", "domain_admin", "superadmin"];

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

  useEffect(() => {
    const cached = getCachedUser();
    if (cached !== null && ADMIN_ROLES.includes(cached.role)) {
      router.replace("/admin");
    }
  }, [router]);

  async function handleSubmit(e: React.FormEvent) {
    e.preventDefault();
    setError("");
    setLoading(true);

    try {
      clearAuthCache();
      const res = await login(username, password);
      const role = res?.user?.role ?? "";
      if (!ADMIN_ROLES.includes(role)) {
        setCachedUser(null);
        setError("Kein Zugriff. Dieses Login ist nur für Admins und Auditoren.");
        return;
      }
      setCachedUser({ username: res.user.username, email: res.user.email, role, list_page_size: res.user.list_page_size });
      if (role === "auditor") {
        router.push("/search");
      } else {
        router.push("/admin");
      }
    } catch {
      setError("Anmeldung fehlgeschlagen. Bitte Zugangsdaten prüfen.");
    } finally {
      setLoading(false);
    }
  }

  return (
    <div className="flex min-h-screen items-center justify-center px-4">
      <Card className="w-full max-w-sm">
        <CardHeader className="text-center">
          <CardTitle className="text-2xl font-bold">archivmail</CardTitle>
          <p className="text-sm text-muted-foreground">Admin-Anmeldung</p>
        </CardHeader>
        <CardContent>
          <form onSubmit={handleSubmit} className="space-y-4">
            <div className="space-y-2">
              <Label htmlFor="username">Benutzername oder E-Mail-Adresse</Label>
              <Input
                id="username"
                type="text"
                placeholder="Benutzername oder E-Mail-Adresse"
                value={username}
                onChange={(e) => setUsername(e.target.value)}
                required
                autoComplete="username"
              />
            </div>
            <div className="space-y-2">
              <Label htmlFor="password">Passwort</Label>
              <Input
                id="password"
                type="password"
                placeholder="Passwort"
                value={password}
                onChange={(e) => setPassword(e.target.value)}
                required
                autoComplete="current-password"
              />
            </div>
            {error && (
              <p className="text-sm text-destructive" role="alert">
                {error}
              </p>
            )}
            <Button type="submit" className="w-full" disabled={loading}>
              {loading ? "Anmelden..." : "Anmelden"}
            </Button>
          </form>
          <div className="mt-4 text-center text-sm text-muted-foreground">
            <a href="/" className="hover:text-foreground underline">
              Zur Benutzer-Anmeldung
            </a>
          </div>
        </CardContent>
      </Card>
    </div>
  );
}
