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

import type { Client } from "@rubis/shared";
import { formatEuros, formatRelativeDate } from "@/lib/format";
import { cn } from "@/lib/utils";

export type ClientWithStats = Client & {
  invoiceCount: number;
  activeInvoiceCount: number;
  lateInvoiceCount: number;
  paidInvoiceCount: number;
  paidLifetimeCents: number;
  pendingLifetimeCents: number;
  lastActivityAt: string | null;
};

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

/**
 * Table desktop des clients.
 *
 * Décisions :
 *  - Ligne cliquable (onClick + role=link + onKeyDown), chevron Link à
 *    droite pour right-click "ouvrir nouvel onglet" (cohérent factures)
 *  - Indicateur de retard : pastille rubis si lateInvoiceCount > 0,
 *    pas un fond rouge agressif
 *  - Encaissé lifetime + actuellement en cours, séparés
 *  - Pas de checkbox actions-en-lot en V1
 */
export function ClientTable({ clients, className }: ClientTableProps) {
  const navigate = useNavigate();
  const goTo = (id: string) => {
    void navigate({ to: "/clients/$id", params: { id } });
  };

  return (
    <div
      className={cn(
        "overflow-hidden rounded-card border border-line bg-white",
        className,
      )}
    >
      <table className="w-full text-left text-[13.5px]">
        <thead>
          <tr className="border-b border-line bg-cream-2/50 text-[11px] font-semibold uppercase tracking-[0.1em] text-ink-3">
            <th scope="col" className="px-5 py-3 font-semibold">Client</th>
            <th scope="col" className="px-3 py-3 font-semibold">Factures actives</th>
            <th scope="col" className="px-3 py-3 font-semibold text-right">En attente</th>
            <th scope="col" className="px-3 py-3 font-semibold text-right">Encaissé</th>
            <th scope="col" className="px-3 py-3 font-semibold">Dernière activité</th>
            <th scope="col" className="px-5 py-3 w-10" aria-label="Actions" />
          </tr>
        </thead>
        <tbody>
          {clients.map((client) => (
            <tr
              key={client.id}
              role="link"
              tabIndex={0}
              aria-label={`Client ${client.name}`}
              onClick={() => goTo(client.id)}
              onKeyDown={(e) => {
                if (e.key === "Enter" || e.key === " ") {
                  e.preventDefault();
                  goTo(client.id);
                }
              }}
              className={cn(
                "border-t border-line first:border-t-0 cursor-pointer",
                "transition-colors hover:bg-cream-2/40",
                "focus-visible:outline-none focus-visible:bg-cream focus-visible:ring-2 focus-visible:ring-rubis-glow focus-visible:ring-inset",
              )}
            >
              <td className="px-5 py-3.5">
                <p className="font-medium text-ink truncate max-w-[260px]">
                  {client.name}
                </p>
                {client.email && (
                  <p className="text-[12px] text-ink-3 truncate max-w-[260px]">
                    {client.email}
                  </p>
                )}
              </td>
              <td className="px-3 py-3.5">
                <div className="flex items-center gap-2">
                  <span className="font-medium text-ink tabular-nums">
                    {client.activeInvoiceCount}
                  </span>
                  {client.lateInvoiceCount > 0 && (
                    <span
                      className="inline-flex items-center gap-1 rounded-full bg-rubis-glow px-2 py-0.5 text-[11px] font-semibold text-rubis-deep"
                      title={`${client.lateInvoiceCount} en retard`}
                    >
                      <AlertCircle size={10} aria-hidden="true" />
                      {client.lateInvoiceCount} retard
                      {client.lateInvoiceCount > 1 ? "s" : ""}
                    </span>
                  )}
                </div>
              </td>
              <td className="px-3 py-3.5 text-right text-ink-2 tabular-nums">
                {client.pendingLifetimeCents > 0 ? (
                  formatEuros(client.pendingLifetimeCents)
                ) : (
                  <span className="text-ink-3">—</span>
                )}
              </td>
              <td className="px-3 py-3.5 text-right tabular-nums">
                {client.paidLifetimeCents > 0 ? (
                  <span className="font-medium text-ink">
                    {formatEuros(client.paidLifetimeCents)}
                  </span>
                ) : (
                  <span className="text-ink-3">—</span>
                )}
              </td>
              <td className="px-3 py-3.5 text-[12.5px] text-ink-3">
                {client.lastActivityAt
                  ? formatRelativeDate(client.lastActivityAt)
                  : "Jamais"}
              </td>
              <td className="px-5 py-3.5">
                <Link
                  to="/clients/$id"
                  params={{ id: client.id }}
                  onClick={(e) => e.stopPropagation()}
                  className="inline-flex size-7 items-center justify-center rounded-default text-ink-3 hover:bg-cream hover:text-rubis"
                  aria-label={`Voir le client ${client.name}`}
                >
                  <ChevronRight size={16} aria-hidden="true" />
                </Link>
              </td>
            </tr>
          ))}
        </tbody>
      </table>
    </div>
  );
}
