"use client";

import { useState, useEffect, Suspense } 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";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";

async function checkInvite(token: string): Promise<string | null> {
  const res = await fetch(`/api/auth/invite?token=${encodeURIComponent(token)}`, {
    credentials: "include",
  });
  if (!res.ok) return null;
  const data = await res.json();
  return data.tenant_name ?? null;
}

async function signup(body: {
  username: string;
  email: string;
  password: string;
  invite?: string;
}): Promise<void> {
  const res = await fetch("/api/auth/signup", {
    method: "POST",
    credentials: "include",
    headers: { "Content-Type": "application/json" },
    body: JSON.stringify(body),
  });
  if (!res.ok) {
    const err = await res.json().catch(() => ({}));
    throw new Error((err as { error?: string }).error ?? "Registrierung fehlgeschlagen");
  }
}

function SignupForm() {
  const router = useRouter();
  const params = useSearchParams();
  const invite = params.get("invite") ?? "";

  const [tenantName, setTenantName] = useState<string | null>(null);
  const [inviteError, setInviteError] = useState("");
  const [username, setUsername] = useState("");
  const [email, setEmail] = useState("");
  const [password, setPassword] = useState("");
  const [loading, setLoading] = useState(false);
  const [done, setDone] = useState(false);
  const [error, setError] = useState("");

  useEffect(() => {
    if (!invite) {
      setInviteError("Registrierung nur mit gültigem Einladungslink möglich.");
      return;
    }
    checkInvite(invite).then((name) => {
      if (name === null) setInviteError("Ungültiger oder abgelaufener Einladungslink.");
      else setTenantName(name);
    });
  }, [invite]);

  const handleSubmit = async (e: React.FormEvent) => {
    e.preventDefault();
    setError("");
    setLoading(true);
    try {
      await signup({ username, email, password, invite: invite || undefined });
      setDone(true);
    } catch (e: unknown) {
      setError(e instanceof Error ? e.message : "Fehler");
    } finally {
      setLoading(false);
    }
  };

  if (done) {
    return (
      <Card className="w-full max-w-sm">
        <CardHeader className="text-center">
          <CardTitle>Fast geschafft!</CardTitle>
        </CardHeader>
        <CardContent className="space-y-4 text-center text-sm text-muted-foreground">
          <p>Wir haben dir eine Bestätigungs-E-Mail gesendet. Bitte klicke auf den Link darin, um deinen Account zu aktivieren.</p>
          <Button variant="outline" className="w-full" onClick={() => router.push("/")}>
            Zur Anmeldung
          </Button>
        </CardContent>
      </Card>
    );
  }

  return (
    <Card className="w-full max-w-sm">
      <CardHeader className="text-center">
        <CardTitle className="text-2xl font-bold">Registrieren</CardTitle>
        {tenantName && (
          <p className="text-sm text-muted-foreground">Einladung zu: <strong>{tenantName}</strong></p>
        )}
      </CardHeader>
      <CardContent>
        {inviteError && (
          <div className="space-y-4">
            <p className="text-sm text-destructive">{inviteError}</p>
            <Button variant="outline" className="w-full" onClick={() => router.push("/")}>
              Zur Anmeldung
            </Button>
          </div>
        )}
        {!inviteError && <form onSubmit={handleSubmit} className="space-y-4">
          <div className="space-y-2">
            <Label htmlFor="username">Benutzername</Label>
            <Input id="username" value={username} onChange={(e) => setUsername(e.target.value)} required autoComplete="username" />
          </div>
          <div className="space-y-2">
            <Label htmlFor="email">E-Mail-Adresse</Label>
            <Input id="email" type="email" value={email} onChange={(e) => setEmail(e.target.value)} required autoComplete="email" />
          </div>
          <div className="space-y-2">
            <Label htmlFor="password">Passwort</Label>
            <Input id="password" type="password" value={password} onChange={(e) => setPassword(e.target.value)} required autoComplete="new-password" minLength={8} />
            <p className="text-xs text-muted-foreground">Mindestens 8 Zeichen</p>
          </div>
          {error && <p className="text-sm text-destructive">{error}</p>}
          <Button type="submit" className="w-full" disabled={loading}>
            {loading ? "Registrierung..." : "Account erstellen"}
          </Button>
        </form>}
        {!inviteError && (
          <p className="mt-4 text-center text-sm text-muted-foreground">
            <a href="/" className="underline hover:text-foreground">Zur Anmeldung</a>
          </p>
        )}
      </CardContent>
    </Card>
  );
}

export default function SignupPage() {
  return (
    <div className="flex min-h-screen items-center justify-center px-4">
      <Suspense>
        <SignupForm />
      </Suspense>
    </div>
  );
}
