"use client";

import * as React from "react";
import { useRouter } from "next/navigation";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { de } from "@/lib/i18n/de";
import { createBrigadeUser, deactivateBrigadeUser } from "@/server/actions/brigade-users";

/**
 * Formular zum Anlegen eines Wehr-Benutzers (lokales Konto). Die Rolle ist auf
 * Wehr-Admin/Lesend beschränkt. Nach Erfolg wird das Einmal-Passwort genau
 * einmal angezeigt.
 */
export function BrigadeUserForm() {
  const router = useRouter();
  const [error, setError] = React.useState<string | null>(null);
  const [tempPassword, setTempPassword] = React.useState<string | null>(null);
  const [pending, startTransition] = React.useTransition();

  function onSubmit(e: React.FormEvent<HTMLFormElement>) {
    e.preventDefault();
    setError(null);
    const form = e.currentTarget;
    const fd = new FormData(form);
    const payload = {
      email: String(fd.get("email") ?? ""),
      name: String(fd.get("name") ?? ""),
      rolle: String(fd.get("rolle") ?? "wehr_read"),
    };
    startTransition(async () => {
      const res = await createBrigadeUser(payload);
      if (!res.ok) {
        setError(res.error);
        return;
      }
      setTempPassword(res.tempPassword);
      form.reset();
      router.refresh();
    });
  }

  return (
    <form
      onSubmit={onSubmit}
      className="space-y-4 rounded border border-rand bg-white p-5"
    >
      <div className="grid gap-1.5 sm:grid-cols-2 sm:gap-4">
        <div className="grid gap-1.5">
          <Label htmlFor="user-name">{de.verwaltung.name}</Label>
          <Input id="user-name" name="name" required />
        </div>
        <div className="grid gap-1.5">
          <Label htmlFor="user-email">{de.verwaltung.email}</Label>
          <Input id="user-email" name="email" type="email" required />
        </div>
        <div className="grid gap-1.5">
          <Label htmlFor="user-rolle">{de.verwaltung.rolle}</Label>
          <select
            id="user-rolle"
            name="rolle"
            defaultValue="wehr_read"
            className="h-10 w-full rounded border border-rand bg-white px-3 text-sm text-anthrazit focus-visible:outline-none focus-visible:ring-2 focus-visible:ring-navy"
          >
            <option value="wehr_read">{de.verwaltung.rolleRead}</option>
            <option value="wehr_admin">{de.verwaltung.rolleAdmin}</option>
          </select>
        </div>
      </div>

      {error ? (
        <p role="alert" className="text-sm text-signal">
          {error}
        </p>
      ) : null}

      {tempPassword ? (
        <div className="rounded border border-bereit/40 bg-bereit/5 p-4">
          <p className="text-sm font-medium text-anthrazit/70">
            {de.verwaltung.tempPasswort}
          </p>
          <code className="mt-1 block rounded border border-rand bg-white px-3 py-2 font-mono text-lg tracking-wide text-navy">
            {tempPassword}
          </code>
        </div>
      ) : null}

      <Button type="submit" disabled={pending}>
        {de.verwaltung.benutzerAnlegen}
      </Button>
    </form>
  );
}

/**
 * Knopf zum Deaktivieren eines Benutzers. Eigener Client-Knopf (Bestätigung +
 * Transition). Selbst-Deaktivierung verhindert die Server-Action zusätzlich.
 */
export function DeactivateUserButton({
  userId,
  disabled,
}: {
  userId: string;
  disabled?: boolean;
}) {
  const router = useRouter();
  const [pending, startTransition] = React.useTransition();
  const [error, setError] = React.useState<string | null>(null);

  function onClick() {
    if (!window.confirm(de.verwaltung.loeschenBestaetigen)) return;
    setError(null);
    startTransition(async () => {
      const res = await deactivateBrigadeUser({ userId });
      if (!res.ok) {
        setError(res.error);
        return;
      }
      router.refresh();
    });
  }

  return (
    <span className="inline-flex flex-col items-end gap-1">
      <Button
        type="button"
        variant="outline"
        size="sm"
        disabled={disabled || pending}
        onClick={onClick}
      >
        {de.verwaltung.deaktivieren}
      </Button>
      {error ? <span className="text-xs text-signal">{error}</span> : null}
    </span>
  );
}
