import Link from "next/link";
import type { ClientWithPayments } from "@/lib/admin-queries";
import { CopyLinkButton } from "@/components/admin/CopyLinkButton";

function fmt(amount: number) {
  return `€${amount.toLocaleString("it-IT", { minimumFractionDigits: 2 })}`;
}

export function ClientRow({ client }: { client: ClientWithPayments }) {
  const incassato = client.payments
    .filter((p) => p.status === "saldato")
    .reduce((sum, p) => sum + parseFloat(p.amount || "0"), 0);

  const daSaldare = client.payments
    .filter((p) => p.status !== "saldato")
    .reduce((sum, p) => sum + parseFloat(p.amount || "0"), 0);

  const slug = client.slug || client.token;
  const path = `/client/${slug}`;

  return (
    <tr className={`hover:bg-muted/40 transition-colors ${client.archived ? "opacity-60" : ""}`}>
      <td className="py-4 px-6">
        <Link
          href={`/admin/clients/${client.id}`}
          className="font-semibold text-foreground hover:text-primary transition-colors"
        >
          {client.name}
        </Link>
        {client.projectBrands && client.projectBrands.length > 0 ? (
          <p className="text-[11px] text-muted-foreground mt-0.5">{client.projectBrands.join(" | ")}</p>
        ) : (
          client.brand_name && (
            <p className="text-[11px] text-muted-foreground mt-0.5">{client.brand_name}</p>
          )
        )}
        {client.archived && (
          <span className="inline-block mt-1 text-[10px] text-muted-foreground bg-muted px-1.5 py-0.5 rounded-full">
            Archiviato
          </span>
        )}
      </td>
      <td className="py-4 px-6 text-right font-mono font-medium text-foreground">
        {fmt(parseFloat(client.ltv))}
      </td>
      <td className="py-4 px-6 text-right">
        {incassato > 0 ? (
          <span className="inline-flex items-center px-2.5 py-0.5 rounded font-mono text-xs font-semibold bg-emerald-50 text-emerald-700 dark:bg-emerald-500/10 dark:text-emerald-400">
            {fmt(incassato)}
          </span>
        ) : (
          <span className="text-muted-foreground/50">—</span>
        )}
      </td>
      <td className="py-4 px-6 text-right font-mono font-medium text-muted-foreground">
        {daSaldare > 0 ? fmt(daSaldare) : <span className="text-muted-foreground/50">—</span>}
      </td>
      <td className="py-4 px-6 text-right">
        <div className="inline-flex items-center gap-2 justify-end">
          <a
            href={path}
            target="_blank"
            rel="noopener noreferrer"
            className="text-xs font-mono text-muted-foreground bg-muted px-2 py-1 rounded border border-border hover:text-foreground transition-colors"
            title={path}
          >
            /client/{slug.slice(0, 12)}…
          </a>
          <CopyLinkButton path={path} title="Copia link profilo" />
        </div>
      </td>
    </tr>
  );
}
