import { Link } from "@tanstack/react-router";
import { AlertCircle } from "lucide-react";

import { formatEuros, formatRelativeDate } from "@/lib/format";
import { cn } from "@/lib/utils";
import type { ClientWithStats } from "./ClientTable";

type ClientCardListProps = {
  clients: ClientWithStats[];
  className?: string;
};

export function ClientCardList({ clients, className }: ClientCardListProps) {
  return (
    <ul className={cn("flex flex-col gap-2", className)}>
      {clients.map((client) => (
        <li key={client.id}>
          <Link
            to="/clients/$id"
            params={{ id: client.id }}
            className={cn(
              "block rounded-card border border-line bg-white p-4",
              "transition-colors hover:border-ink-3",
              "focus-visible:outline-none focus-visible:ring-4 focus-visible:ring-rubis-glow",
            )}
          >
            <div className="flex items-start justify-between gap-3">
              <div className="min-w-0">
                <p className="text-[14.5px] font-semibold text-ink truncate">
                  {client.name}
                </p>
                {client.email && (
                  <p className="mt-0.5 text-[12px] text-ink-3 truncate">
                    {client.email}
                  </p>
                )}
              </div>
              {client.lateInvoiceCount > 0 && (
                <span className="shrink-0 inline-flex items-center gap-1 rounded-full bg-rubis-glow px-2 py-0.5 text-[11px] font-semibold text-rubis-deep">
                  <AlertCircle size={10} aria-hidden="true" />
                  {client.lateInvoiceCount}
                </span>
              )}
            </div>

            <div className="mt-3 grid grid-cols-2 gap-3 text-[12px]">
              <div>
                <p className="text-[10.5px] font-semibold uppercase tracking-[0.12em] text-ink-3">
                  Actives
                </p>
                <p className="mt-0.5 font-medium text-ink tabular-nums">
                  {client.activeInvoiceCount}
                </p>
              </div>
              <div>
                <p className="text-[10.5px] font-semibold uppercase tracking-[0.12em] text-ink-3">
                  Encaissé
                </p>
                <p className="mt-0.5 font-medium text-ink tabular-nums">
                  {client.paidLifetimeCents > 0
                    ? formatEuros(client.paidLifetimeCents)
                    : "—"}
                </p>
              </div>
            </div>

            {client.lastActivityAt && (
              <p className="mt-3 text-[11.5px] text-ink-3">
                Dernière activité {formatRelativeDate(client.lastActivityAt)}
              </p>
            )}
          </Link>
        </li>
      ))}
    </ul>
  );
}
