"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 { promoteMerkmal, mergeMerkmal } from "../../../_actions/proposals";

export interface ProposalRow {
  id: string;
  name: string;
  typ: string;
}
export interface ActiveTarget {
  id: string;
  name: string;
  typ: string;
}

const TYP_LABELS: Record<string, string> = {
  number: "Zahl",
  enum: "Auswahl",
  boolean: "Ja/Nein",
  text: "Text",
};
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";

/**
 * Governance-Flow für vorgeschlagene Merkmale: Übernehmen (promote -> active)
 * oder in ein typkompatibles aktives Merkmal Zusammenführen (merge). Die
 * Typ-Kompatibilität wird zusätzlich serverseitig erzwungen; die UI bietet nur
 * gleichtypige Ziele an.
 */
export function ProposalsClient({
  proposals,
  targets,
}: {
  proposals: ProposalRow[];
  targets: ActiveTarget[];
}) {
  const router = useRouter();
  const [error, setError] = React.useState<string | null>(null);
  const [zielByRow, setZielByRow] = React.useState<Record<string, string>>({});
  const [pending, startTransition] = React.useTransition();

  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();
    });
  }

  if (proposals.length === 0) {
    return (
      <div>
        <h1 className="mb-6 font-display text-2xl text-navy">
          {de.admin.navVorschlaege}
        </h1>
        <p className="rounded border border-rand bg-white px-4 py-6 text-sm text-anthrazit/60">
          {de.admin.keineEintraege}
        </p>
      </div>
    );
  }

  return (
    <div className="space-y-4">
      <h1 className="font-display text-2xl text-navy">
        {de.admin.navVorschlaege}
      </h1>
      {error && <p className="text-sm text-signal">{error}</p>}
      <ul className="space-y-2">
        {proposals.map((p) => {
          const kompatibel = targets.filter((t) => t.typ === p.typ);
          return (
            <li
              key={p.id}
              className="flex flex-wrap items-center justify-between gap-3 rounded border border-rand bg-white px-4 py-3"
            >
              <div>
                <span className="font-medium text-anthrazit">{p.name}</span>
                <span className="ml-2 text-sm text-anthrazit/60">
                  {TYP_LABELS[p.typ] ?? p.typ}
                </span>
              </div>
              <div className="flex flex-wrap items-center gap-2">
                <Button
                  size="sm"
                  disabled={pending}
                  onClick={() => run(() => promoteMerkmal(p.id))}
                >
                  {de.admin.promote}
                </Button>
                {kompatibel.length > 0 && (
                  <>
                    <select
                      className={selectCls}
                      value={zielByRow[p.id] ?? ""}
                      onChange={(e) =>
                        setZielByRow((prev) => ({
                          ...prev,
                          [p.id]: e.target.value,
                        }))
                      }
                    >
                      <option value="">{de.admin.mergeZiel} …</option>
                      {kompatibel.map((t) => (
                        <option key={t.id} value={t.id}>
                          {t.name}
                        </option>
                      ))}
                    </select>
                    <Button
                      size="sm"
                      variant="outline"
                      disabled={pending || !zielByRow[p.id]}
                      onClick={() =>
                        run(() =>
                          mergeMerkmal({
                            proposedId: p.id,
                            zielId: zielByRow[p.id],
                          }),
                        )
                      }
                    >
                      {de.admin.merge}
                    </Button>
                  </>
                )}
              </div>
            </li>
          );
        })}
      </ul>
    </div>
  );
}
