import Link from "next/link";
import { getAllClientsWithPayments } from "@/lib/admin-queries";
import { ClientRow } from "@/components/admin/ClientRow";
import { Button } from "@/components/ui/button";
import { PageHeader } from "@/components/admin/PageHeader";

export const revalidate = 0;

export default async function AdminClientsPage({
  searchParams,
}: {
  searchParams: Promise<{ archived?: string }>;
}) {
  const { archived } = await searchParams;
  const showArchived = archived === "1";
  const clients = await getAllClientsWithPayments(showArchived);

  const clientiAction = (
    <div className="flex items-center gap-3">
      <a
        href={showArchived ? "/admin/clients" : "/admin/clients?archived=1"}
        className="text-xs text-[#71717a] hover:text-[#1A463C] underline underline-offset-2"
      >
        {showArchived ? "Nascondi archiviati" : "Mostra archiviati"}
      </a>
      <Button asChild>
        <Link href="/admin/clients/new">+ Nuovo cliente</Link>
      </Button>
    </div>
  );

  return (
    <div className="space-y-6">
      <PageHeader title="Clienti" action={clientiAction} />

      {clients.length === 0 ? (
        <div className="text-center py-20 text-[#71717a]">
          <p>{showArchived ? "Nessun cliente archiviato." : "Nessun cliente ancora."}</p>
          {!showArchived && (
            <p className="mt-2">
              <Link href="/admin/clients/new" className="text-[#1A463C] hover:underline font-medium">
                Crea il primo cliente
              </Link>
            </p>
          )}
        </div>
      ) : (
        <div className="bg-white rounded-lg border border-[#e5e7eb] overflow-hidden">
          <table className="w-full text-sm">
            <thead className="bg-[#f9f9f9] border-b border-[#e5e7eb]">
              <tr>
                <th className="text-left py-3 px-4 font-medium text-[#71717a]">Cliente</th>
                <th className="text-left py-3 px-4 font-medium text-[#71717a]">LTV</th>
                <th className="text-left py-3 px-4 font-medium text-[#71717a]">Importo incassato</th>
                <th className="text-left py-3 px-4 font-medium text-[#71717a]">Importo da saldare</th>
                <th className="text-left py-3 px-4 font-medium text-[#71717a]">Link</th>
              </tr>
            </thead>
            <tbody>
              {clients.map((client) => (
                <ClientRow key={client.id} client={client} />
              ))}
            </tbody>
          </table>
        </div>
      )}
    </div>
  );
}
