"use client";

/**
 * AuditDiffViewer — prikazuje "before vs after" za audit entry-je čiji
 * meta sadrži `before` i `after` ključeve.
 *
 * Audit save akcije obavezno snimaju `meta: { before, after }` da bi diff
 * mogao da se renderuje. Ostalim audit-ima koji nemaju diff strukturu,
 * komponenta vraća null.
 */

type DiffMeta = {
  before?: Record<string, unknown>;
  after?: Record<string, unknown>;
};

export function AuditDiffViewer({ meta }: { meta: unknown }) {
  if (!meta || typeof meta !== "object") return null;
  const m = meta as DiffMeta;
  if (!m.before && !m.after) return null;

  const allKeys = new Set([
    ...Object.keys(m.before ?? {}),
    ...Object.keys(m.after ?? {}),
  ]);
  const diffRows = [...allKeys]
    .map((key) => {
      const b = m.before?.[key];
      const a = m.after?.[key];
      const bStr = formatValue(b);
      const aStr = formatValue(a);
      const changed = bStr !== aStr;
      return { key, before: bStr, after: aStr, changed };
    })
    .filter((r) => r.changed);

  if (diffRows.length === 0) {
    return <p className="text-xs text-muted-foreground">Nema vidljivih promena.</p>;
  }

  return (
    <div className="mt-2 overflow-x-auto rounded-lg border border-border bg-zinc-50 text-xs">
      <table className="w-full">
        <thead>
          <tr className="border-b border-border bg-white text-left">
            <th className="px-2 py-1.5 font-bold">Polje</th>
            <th className="px-2 py-1.5 font-bold text-rose-700">Pre</th>
            <th className="px-2 py-1.5 font-bold text-emerald-700">Posle</th>
          </tr>
        </thead>
        <tbody>
          {diffRows.map((row) => (
            <tr key={row.key} className="border-b border-border/50">
              <td className="px-2 py-1 font-mono font-semibold">{row.key}</td>
              <td className="px-2 py-1 font-mono text-rose-700">{row.before || "—"}</td>
              <td className="px-2 py-1 font-mono text-emerald-700">{row.after || "—"}</td>
            </tr>
          ))}
        </tbody>
      </table>
    </div>
  );
}

function formatValue(v: unknown): string {
  if (v === null || v === undefined) return "";
  if (typeof v === "boolean") return v ? "✓ true" : "✗ false";
  if (typeof v === "string") return v.length > 80 ? `${v.slice(0, 80)}…` : v;
  if (typeof v === "number") return String(v);
  return JSON.stringify(v).slice(0, 100);
}
