"use client";

import Link from "next/link";
import { useActionState } from "react";
import { confirmMfaEnrollment, type EnrollState } from "@/server/actions/platform";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";

const initial: EnrollState = { status: "idle" };

export function PlatformEnrollForm() {
  const [state, action, pending] = useActionState(confirmMfaEnrollment, initial);

  if (state.status === "done") {
    return (
      <div className="space-y-4">
        <div className="rounded-lg bg-[rgba(46,204,113,0.14)] px-3 py-2 text-sm text-[var(--ok)]">
          MFA ist aktiv. Bewahren Sie die folgenden Recovery-Codes sicher auf — sie werden
          <strong> nur jetzt</strong> angezeigt und ermöglichen den Zugang, falls der Authenticator verloren geht.
        </div>
        <ul className="grid grid-cols-2 gap-2 font-mono text-sm">
          {state.recoveryCodes.map((c) => (
            <li key={c} className="rounded border bg-card px-3 py-1.5 text-center tracking-wider">{c}</li>
          ))}
        </ul>
        <Button nativeButton={false} render={<Link href="/admin" />} className="w-full">
          Codes gesichert — zur Admin-Konsole
        </Button>
      </div>
    );
  }

  return (
    <form action={action} className="space-y-4">
      <div>
        <Label htmlFor="token">6-stelliger Code aus der Authenticator-App</Label>
        <Input
          id="token"
          name="token"
          inputMode="numeric"
          autoComplete="one-time-code"
          placeholder="123456"
          required
          className="mt-1"
        />
      </div>
      {state.status === "error" && (
        <p role="alert" className="rounded-lg bg-[rgba(255,107,107,0.16)] px-3 py-2 text-sm text-[var(--risk)]">
          {state.message}
        </p>
      )}
      <Button type="submit" disabled={pending} className="w-full">
        {pending ? "Prüfe…" : "MFA aktivieren"}
      </Button>
    </form>
  );
}
