"use client";

import { Suspense, useState } from "react";
import { useRouter, useSearchParams } from "next/navigation";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";

/**
 * Validiert Redirect-URL: nur interne Routes erlauben
 * Verhindert Open Redirect zu externen Seiten
 */
function isInternalUrl(url: string): boolean {
  if (!url.startsWith("/")) return false;
  // Nur Admin- und Kunden-Routes erlauben
  return url.startsWith("/admin/") || url.startsWith("/kunden/");
}

function AdminLoginForm() {
  const router = useRouter();
  const searchParams = useSearchParams();
  const rawFrom = searchParams.get("from");
  // ✅ Validierung: nur interne URLs erlauben, Fallback auf /admin/anfragen
  const from = rawFrom && isInternalUrl(rawFrom) ? rawFrom : "/admin/anfragen";
  const sessionExpired = searchParams.get("session_expired") === "true";

  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");
  const [error, setError] = useState(
    sessionExpired ? "Ihre Session ist abgelaufen. Bitte melden Sie sich erneut an." : ""
  );
  const [loading, setLoading] = useState(false);

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

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

    if (res.ok) {
      router.push(from);
    } else {
      setError("Ungültige Zugangsdaten");
    }
    setLoading(false);
  }

  return (
    <div className="min-h-screen bg-[#f5f5f4] flex items-center justify-center px-4">
      <div className="bg-white border border-slate-200 p-8 w-full max-w-sm">
        <div className="mb-6">
          <h1 className="text-xl font-bold text-[#1c1917] tracking-tight">
            Admin · Mietpark Hahn
          </h1>
          <p className="text-sm text-slate-500 mt-1">Bitte anmelden</p>
        </div>

        <form onSubmit={handleSubmit} className="space-y-4">
          <div>
            <Label htmlFor="email">E-Mail</Label>
            <Input
              id="email"
              type="email"
              value={email}
              onChange={(e) => setEmail(e.target.value)}
              autoComplete="email"
              placeholder="admin@beispiel.de"
              className="mt-1 rounded-md"
              required
            />
          </div>
          <div>
            <Label htmlFor="password">Passwort</Label>
            <Input
              id="password"
              type="password"
              value={password}
              onChange={(e) => setPassword(e.target.value)}
              autoComplete="current-password"
              className="mt-1 rounded-md"
              required
            />
          </div>

          {error && (
            <p className={`text-sm ${sessionExpired ? "text-blue-600" : "text-red-500"}`}>
              {error}
            </p>
          )}

          <Button
            type="submit"
            disabled={loading}
            className="w-full bg-[#1c1917] hover:bg-[#44403c] text-white rounded-md font-semibold border-transparent"
          >
            {loading ? "Wird geprüft…" : "Anmelden"}
          </Button>
        </form>
      </div>
    </div>
  );
}

export default function AdminLoginPage() {
  return (
    <Suspense>
      <AdminLoginForm />
    </Suspense>
  );
}
