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

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

  return (
    <tr className={`border-b border-[#f4f4f5] hover:bg-[#f9f9f9] transition-colors ${client.archived ? "opacity-60" : ""}`}>
      <td className="py-3 px-4">
        <Link
          href={`/admin/clients/${client.id}`}
          className="font-medium text-[#1a1a1a] hover:text-[#1A463C] hover:underline"
        >
          {client.name}
        </Link>
        {client.projectBrands && client.projectBrands.length > 0 ? (
          <p className="text-xs text-[#71717a] mt-0.5">{client.projectBrands.join(" | ")}</p>
        ) : (
          <p className="text-xs text-[#71717a]">{client.brand_name}</p>
        )}
        {client.archived && (
          <span className="text-[10px] text-[#71717a] bg-[#f4f4f5] px-1.5 py-0.5 rounded-full">
            Archiviato
          </span>
        )}
      </td>
      <td className="py-3 px-4 text-sm text-[#1a1a1a]">
        {fmt(parseFloat(client.ltv))}
      </td>
      <td className="py-3 px-4 text-sm text-[#1a1a1a]">
        {incassato > 0 ? (
          <span className="text-[#16a34a] font-medium">{fmt(incassato)}</span>
        ) : (
          <span className="text-[#71717a]">—</span>
        )}
      </td>
      <td className="py-3 px-4 text-sm">
        {daSaldare > 0 ? (
          <span className="text-[#1a1a1a]">{fmt(daSaldare)}</span>
        ) : (
          <span className="text-[#71717a]">—</span>
        )}
      </td>
      <td className="py-3 px-4">
        <a
          href={`/client/${client.slug || client.token}`}
          target="_blank"
          rel="noopener noreferrer"
          className="text-xs text-[#1A463C] hover:underline font-mono"
        >
          /client/{(client.slug || client.token).slice(0, 12)}…
        </a>
      </td>
    </tr>
  );
}