"use client";

import * as React from "react";
import { useRouter } from "next/navigation";
import { Button } from "@/components/ui/button";
import { de } from "@/lib/i18n/de";
import {
  MerkmalEditor,
  type MerkmalEditorValue,
} from "./MerkmalEditor";
import { deleteMerkmal } from "../../_actions/merkmale";

export interface MerkmalRow extends MerkmalEditorValue {
  id: string;
}

const TYP_LABELS: Record<string, string> = {
  number: "Zahl",
  enum: "Auswahl",
  boolean: "Ja/Nein",
  text: "Text",
};

/**
 * Client-Hülle der Merkmal-Liste: Anlegen/Bearbeiten via MerkmalEditor, Löschen
 * mit klarer Fehlermeldung (kein 500), wenn referenziert. Die Server-Action ist
 * guarded + Zod-validiert.
 */
export function MerkmalListClient({ rows }: { rows: MerkmalRow[] }) {
  const router = useRouter();
  const [creating, setCreating] = React.useState(false);
  const [editId, setEditId] = React.useState<string | null>(null);
  const [error, setError] = React.useState<string | null>(null);
  const [pending, startTransition] = React.useTransition();

  function remove(id: string) {
    setError(null);
    startTransition(async () => {
      const res = await deleteMerkmal(id);
      if (!res.ok) {
        setError(res.error);
        return;
      }
      router.refresh();
    });
  }

  return (
    <div className="space-y-4">
      <div className="flex items-center justify-between">
        <h1 className="font-display text-2xl text-navy">
          {de.admin.navMerkmale}
        </h1>
        {!creating && (
          <Button onClick={() => setCreating(true)}>{de.admin.neu}</Button>
        )}
      </div>

      {creating && <MerkmalEditor onDone={() => setCreating(false)} />}
      {error && <p className="text-sm text-signal">{error}</p>}

      {rows.length === 0 ? (
        <p className="rounded border border-rand bg-white px-4 py-6 text-sm text-anthrazit/60">
          {de.admin.keineEintraege}
        </p>
      ) : (
        <ul className="space-y-2">
          {rows.map((m) => (
            <li
              key={m.id}
              className="rounded border border-rand bg-white px-4 py-3"
            >
              {editId === m.id ? (
                <MerkmalEditor
                  initial={m}
                  onDone={() => setEditId(null)}
                />
              ) : (
                <div className="flex flex-wrap items-center justify-between gap-3">
                  <div>
                    <span className="font-medium text-anthrazit">{m.name}</span>
                    <span className="ml-2 text-sm text-anthrazit/60">
                      {TYP_LABELS[m.typ] ?? m.typ}
                      {m.einheit ? ` · ${m.einheit}` : ""}
                    </span>
                  </div>
                  <div className="flex gap-2">
                    <Button
                      variant="outline"
                      size="sm"
                      onClick={() => setEditId(m.id)}
                    >
                      {de.admin.bearbeiten}
                    </Button>
                    <Button
                      variant="ghost"
                      size="sm"
                      disabled={pending}
                      onClick={() => remove(m.id)}
                    >
                      {de.admin.loeschen}
                    </Button>
                  </div>
                </div>
              )}
            </li>
          ))}
        </ul>
      )}
    </div>
  );
}
