"use client";

import * as React from "react";
import { Button } from "@/components/ui/button";
import { de } from "@/lib/i18n/de";
import { resetBrigadeUserPassword } from "../../../_actions/brigades";

/**
 * Setzt das Passwort eines lokalen Wehr-Benutzers zurück und zeigt das neue
 * Einmal-Passwort genau einmal. Authentik-Konten haben keinen Button.
 */
export function UserResetButton({
  userId,
  authTyp,
}: {
  userId: string;
  authTyp: string;
}) {
  const [error, setError] = React.useState<string | null>(null);
  const [pw, setPw] = React.useState<string | null>(null);
  const [pending, startTransition] = React.useTransition();

  if (authTyp !== "local") {
    return <span className="text-xs text-anthrazit/40">Authentik</span>;
  }

  if (pw) {
    return (
      <code className="rounded border border-rand bg-white px-2 py-1 font-mono text-xs text-navy">
        {pw}
      </code>
    );
  }

  return (
    <div className="flex flex-col items-end gap-1">
      <Button
        variant="outline"
        size="sm"
        disabled={pending}
        onClick={() =>
          startTransition(async () => {
            setError(null);
            const res = await resetBrigadeUserPassword({ userId });
            if (!res.ok) {
              setError(res.error);
              return;
            }
            setPw(res.tempPassword);
          })
        }
      >
        {de.admin.passwortReset}
      </Button>
      {error && <span className="text-xs text-signal">{error}</span>}
    </div>
  );
}
