import { createFileRoute } from "@tanstack/react-router";
import { useQuery } from "@tanstack/react-query";
import { useServerFn } from "@tanstack/react-start";
import { listCustomers } from "@/lib/admin.functions";
import { Card } from "@/components/ui/card";
import { formatBDT } from "@/lib/format";
import { Copy } from "lucide-react";
import { toast } from "sonner";

export const Route = createFileRoute("/admin/customers")({
  component: CustomersPage,
});

function CustomersPage() {
  const fn = useServerFn(listCustomers);
  const { data, isLoading } = useQuery({ queryKey: ["admin", "customers"], queryFn: () => fn() });

  return (
    <Card className="p-0 overflow-hidden">
      <table className="w-full text-sm">
        <thead className="bg-muted/50 text-left">
          <tr><th className="p-3">Email</th><th className="p-3">WhatsApp</th><th className="p-3">Orders</th><th className="p-3">Spend</th><th className="p-3">Last Order</th></tr>
        </thead>
        <tbody>
          {isLoading && <tr><td colSpan={5} className="p-6 text-center text-muted-foreground">Loading...</td></tr>}
          {!isLoading && data?.length === 0 && <tr><td colSpan={5} className="p-6 text-center text-muted-foreground">No customers</td></tr>}
          {data?.map((c: any) => (
            <tr key={c.email} className="border-t">
              <td className="p-3">
                <button className="flex items-center gap-2" onClick={() => { navigator.clipboard.writeText(c.email); toast.success("Copied"); }}>
                  {c.email} <Copy className="w-3 h-3 text-muted-foreground" />
                </button>
              </td>
              <td className="p-3">{c.whatsapp ?? "—"}</td>
              <td className="p-3">{c.orders}</td>
              <td className="p-3 font-medium">{formatBDT(c.spend)}</td>
              <td className="p-3 text-xs text-muted-foreground">{new Date(c.last).toLocaleString()}</td>
            </tr>
          ))}
        </tbody>
      </table>
    </Card>
  );
}