"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 { de } from "@/lib/i18n/de";
import { createCategory } from "../../_actions/equipment-categories";

/** Inline-Anlageformular für eine neue Geräte-Kategorie. */
export function CategoryCreateForm() {
  const router = useRouter();
  const [open, setOpen] = React.useState(false);
  const [name, setName] = React.useState("");
  const [error, setError] = React.useState<string | null>(null);
  const [pending, startTransition] = React.useTransition();

  function submit() {
    setError(null);
    startTransition(async () => {
      const res = await createCategory({ name });
      if (!res.ok) {
        setError(res.error);
        return;
      }
      setName("");
      setOpen(false);
      router.refresh();
    });
  }

  if (!open) {
    return <Button onClick={() => setOpen(true)}>{de.admin.neu}</Button>;
  }

  return (
    <div className="flex flex-wrap items-end gap-2 rounded border border-rand bg-white p-4">
      <label className="text-sm">
        <span className="mb-1 block font-medium text-anthrazit/70">
          {de.admin.name}
        </span>
        <Input value={name} onChange={(e) => setName(e.target.value)} />
      </label>
      {error && <p className="w-full text-sm text-signal">{error}</p>}
      <Button onClick={submit} disabled={pending}>
        {de.admin.anlegen}
      </Button>
      <Button variant="ghost" onClick={() => setOpen(false)}>
        {de.admin.abbrechen}
      </Button>
    </div>
  );
}
