"use client";

import { useTransition } from "react";
import { useRouter } from "next/navigation";
import { adminMarkVoucherPaidAction, adminCancelVoucherAction } from "@/lib/actions/vouchers";
import { formatDateTimeDE } from "@/lib/orderConstants";

const fmt = (n: number) => new Intl.NumberFormat("de-DE", { style: "currency", currency: "EUR" }).format(n);

export function VoucherRow({
  item,
}: {
  item: {
    id: string;
    code: string;
    amount: number;
    purchaserName: string;
    purchaserEmail: string;
    recipientName: string;
    message: string;
    paid: boolean;
    paymentMethod: string;
    cancelled: boolean;
    redeemed: boolean;
    createdAt: string;
  };
}) {
  const [pending, startTransition] = useTransition();
  const router = useRouter();

  const status = item.cancelled
    ? { label: "Storniert", color: "text-[var(--rk-ink-muted)]" }
    : item.redeemed
      ? { label: "Eingelöst", color: "text-[var(--rk-ink-muted)]" }
      : item.paid
        ? { label: "Bezahlt", color: "text-emerald-400" }
        : { label: "Offen", color: "text-amber-400" };

  return (
    <div className={`bg-[var(--rk-surface)] border border-white/10 rounded-2xl p-5 ${item.cancelled ? "opacity-50" : ""}`}>
      <div className="flex items-center justify-between gap-3 flex-wrap">
        <div className="min-w-0">
          <p className="text-sm">
            {item.code ? <span className="font-mono">{item.code}</span> : <span className="text-[var(--rk-ink-muted)]">Noch kein Code</span>}
            <span className="ml-2 font-medium">{fmt(item.amount)}</span>
          </p>
          <p className="text-xs text-[var(--rk-ink-muted)] mt-0.5">
            {item.purchaserName} · {item.purchaserEmail}
            {item.recipientName ? ` · für ${item.recipientName}` : ""}
          </p>
          {item.message && <p className="text-xs text-[var(--rk-ink-muted)] mt-0.5">„{item.message}"</p>}
        </div>
        <div className="flex items-center gap-3 shrink-0">
          <span className={`text-[0.65rem] uppercase tracking-[0.1em] ${status.color}`}>{status.label}</span>
          {!item.paid && !item.cancelled && (
            <button
              disabled={pending}
              onClick={() => startTransition(async () => { await adminMarkVoucherPaidAction(item.id); router.refresh(); })}
              className="text-xs border border-emerald-400/40 text-emerald-400 rounded-lg px-3 py-1.5 hover:border-emerald-400 disabled:opacity-50"
            >
              Als bezahlt bestätigen
            </button>
          )}
          {!item.cancelled && !item.redeemed && (
            <button
              disabled={pending}
              onClick={() => {
                if (confirm("Diesen Gutschein wirklich stornieren?")) {
                  startTransition(async () => { await adminCancelVoucherAction(item.id); router.refresh(); });
                }
              }}
              className="text-xs text-red-400/80 hover:text-red-400 transition-colors disabled:opacity-50"
            >
              Stornieren
            </button>
          )}
        </div>
      </div>
      <p className="mt-2 text-[0.65rem] text-[var(--rk-ink-muted)]">
        Angefragt: {formatDateTimeDE(new Date(item.createdAt))}
        {item.paymentMethod && ` · ${item.paymentMethod === "stripe" ? "Online (Stripe)" : "Manuell bestätigt"}`}
      </p>
    </div>
  );
}
