"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 { createTemplate } from "../../_actions/templates";

/** Inline-Anlageformular für eine neue Fahrzeug-Vorlage. */
export function TemplateCreateForm() {
  const router = useRouter();
  const [open, setOpen] = React.useState(false);
  const [code, setCode] = React.useState("");
  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 createTemplate({ code, name });
      if (!res.ok) {
        setError(res.error);
        return;
      }
      setCode("");
      setName("");
      setOpen(false);
      router.refresh();
    });
  }

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

  return (
    <div className="space-y-3 rounded border border-rand bg-white p-4">
      <div className="grid gap-3 sm:grid-cols-2">
        <label className="text-sm">
          <span className="mb-1 block font-medium text-anthrazit/70">
            {de.admin.code}
          </span>
          <Input value={code} onChange={(e) => setCode(e.target.value)} />
        </label>
        <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>
      </div>
      {error && <p className="text-sm text-signal">{error}</p>}
      <div className="flex gap-2">
        <Button onClick={submit} disabled={pending}>
          {de.admin.anlegen}
        </Button>
        <Button variant="ghost" onClick={() => setOpen(false)}>
          {de.admin.abbrechen}
        </Button>
      </div>
    </div>
  );
}
