"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 {
  setCategoryMerkmal,
  removeCategoryMerkmal,
} from "../../../_actions/equipment-categories";

export interface CategoryMerkmalRow {
  merkmalId: string;
  name: string;
  einheit: string | null;
  reihenfolge: number;
}
export interface MerkmalLite {
  id: string;
  name: string;
}

const selectCls =
  "h-9 rounded border border-rand bg-white px-2 text-sm text-anthrazit focus:outline-none focus:ring-2 focus:ring-navy";

/**
 * Editor der Merkmale einer Geräte-Kategorie (Reihenfolge stabil sortiert).
 * Aktionen über guarded + Zod-validierte Server-Actions.
 */
export function CategoryMerkmaleEditor({
  categoryId,
  rows,
  alleMerkmale,
}: {
  categoryId: string;
  rows: CategoryMerkmalRow[];
  alleMerkmale: MerkmalLite[];
}) {
  const router = useRouter();
  const [error, setError] = React.useState<string | null>(null);
  const [addId, setAddId] = React.useState("");
  const [pending, startTransition] = React.useTransition();

  const zugeordnet = new Set(rows.map((r) => r.merkmalId));
  const verfuegbar = alleMerkmale.filter((m) => !zugeordnet.has(m.id));

  function run(fn: () => Promise<{ ok: boolean; error?: string }>) {
    setError(null);
    startTransition(async () => {
      const res = await fn();
      if (!res.ok) {
        setError(res.error ?? de.fehler.allgemein);
        return;
      }
      router.refresh();
    });
  }

  return (
    <section className="space-y-3">
      <h2 className="font-display text-lg text-navy">{de.admin.navMerkmale}</h2>
      {error && <p className="text-sm text-signal">{error}</p>}

      {rows.length === 0 ? (
        <p className="rounded border border-rand bg-white px-4 py-4 text-sm text-anthrazit/60">
          {de.admin.keineEintraege}
        </p>
      ) : (
        <ol className="space-y-2">
          {rows.map((r, i) => (
            <li
              key={r.merkmalId}
              className="flex items-center justify-between gap-3 rounded border border-rand bg-white px-4 py-2"
            >
              <span className="text-anthrazit">
                <span className="mr-2 text-anthrazit/40">{i + 1}.</span>
                {r.name}
                {r.einheit && (
                  <span className="ml-1 text-anthrazit/60">({r.einheit})</span>
                )}
              </span>
              <Button
                variant="ghost"
                size="sm"
                disabled={pending}
                onClick={() =>
                  run(() =>
                    removeCategoryMerkmal({
                      categoryId,
                      merkmalId: r.merkmalId,
                    }),
                  )
                }
              >
                {de.admin.loeschen}
              </Button>
            </li>
          ))}
        </ol>
      )}

      {verfuegbar.length > 0 && (
        <div className="flex flex-wrap items-end gap-2 rounded border border-rand/70 bg-white p-3">
          <select
            className={selectCls}
            value={addId}
            onChange={(e) => setAddId(e.target.value)}
          >
            <option value="">{de.admin.navMerkmale} …</option>
            {verfuegbar.map((m) => (
              <option key={m.id} value={m.id}>
                {m.name}
              </option>
            ))}
          </select>
          <Button
            size="sm"
            disabled={pending || !addId}
            onClick={() => {
              run(() =>
                setCategoryMerkmal({
                  categoryId,
                  merkmal: { merkmalId: addId, reihenfolge: rows.length },
                }),
              );
              setAddId("");
            }}
          >
            {de.admin.anlegen}
          </Button>
        </div>
      )}
    </section>
  );
}
