"use client";

import { useTransition } from "react";
import { useRouter } from "next/navigation";
import { removeOrderDiscountAction } from "@/lib/actions/discounts";
import { getPayableAmount } from "@/lib/discounts";

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

export function AdminDiscountPanel({
  orderId,
  discountCode,
  discountAmount,
  manualDiscountAmount = 0,
  latestAmount,
  showPayable,
}: {
  orderId: string;
  discountCode: string;
  discountAmount: number;
  manualDiscountAmount?: number;
  latestAmount: number;
  showPayable: boolean;
}) {
  const [pending, startTransition] = useTransition();
  const router = useRouter();

  if (!discountCode) return null;

  return (
    <div className="border border-white/10 rounded-xl p-5">
      <p className="text-xs uppercase tracking-[0.1em] text-[var(--rk-ink-muted)] mb-2">Rabattcode</p>
      <div className="flex items-center justify-between gap-3 flex-wrap">
        <p className="text-sm text-emerald-400">
          <span className="font-mono">{discountCode}</span> · −{fmt(discountAmount)}
          {showPayable && (
            <span className="text-[var(--rk-ink)]">
              {" "}
              · zu zahlen: {fmt(getPayableAmount(latestAmount, discountAmount + manualDiscountAmount))}
            </span>
          )}
        </p>
        <button
          disabled={pending}
          onClick={() => {
            if (confirm("Diesen Rabattcode vom Auftrag entfernen?")) {
              startTransition(async () => {
                const result = await removeOrderDiscountAction(orderId);
                if (result?.error) alert(result.error);
                router.refresh();
              });
            }
          }}
          className="text-xs text-red-400/80 hover:text-red-400 transition-colors disabled:opacity-50"
        >
          Entfernen
        </button>
      </div>
    </div>
  );
}
