import { createFileRoute, Link } from "@tanstack/react-router";
import { useQuery } from "@tanstack/react-query";
import { useServerFn } from "@tanstack/react-start";
import { getDashboardStats } from "@/lib/admin.functions";
import { Card } from "@/components/ui/card";
import { Badge } from "@/components/ui/badge";
import { formatBDT } from "@/lib/format";
import { ShoppingBag, Clock, CheckCircle2, Truck, DollarSign, Users } from "lucide-react";

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

const statusColor: Record<string, string> = {
  pending: "bg-amber-500/15 text-amber-700 dark:text-amber-400",
  verified: "bg-blue-500/15 text-blue-700 dark:text-blue-400",
  delivered: "bg-green-500/15 text-green-700 dark:text-green-400",
  rejected: "bg-red-500/15 text-red-700 dark:text-red-400",
};

function DashboardHome() {
  const fn = useServerFn(getDashboardStats);
  const { data, isLoading } = useQuery({ queryKey: ["admin", "stats"], queryFn: () => fn() });

  if (isLoading || !data) return <div className="text-muted-foreground">Loading stats...</div>;

  const cards = [
    { label: "Total Orders", value: data.total, icon: ShoppingBag, color: "text-foreground" },
    { label: "Pending", value: data.pending, icon: Clock, color: "text-amber-600" },
    { label: "Verified", value: data.verified, icon: CheckCircle2, color: "text-blue-600" },
    { label: "Delivered", value: data.delivered, icon: Truck, color: "text-green-600" },
    { label: "Revenue", value: formatBDT(data.revenue), icon: DollarSign, color: "text-foreground" },
    { label: "Customers", value: data.customers, icon: Users, color: "text-foreground" },
  ];

  return (
    <div className="space-y-6">
      <div className="grid gap-4 grid-cols-2 lg:grid-cols-3 xl:grid-cols-6">
        {cards.map((c) => {
          const Icon = c.icon;
          return (
            <Card key={c.label} className="p-4">
              <div className="flex items-center justify-between">
                <p className="text-xs text-muted-foreground">{c.label}</p>
                <Icon className={`w-4 h-4 ${c.color}`} />
              </div>
              <p className="mt-2 text-2xl font-bold">{c.value}</p>
            </Card>
          );
        })}
      </div>

      <Card className="p-6">
        <div className="flex items-center justify-between mb-4">
          <h2 className="font-semibold">Recent Orders</h2>
          <Link to="/admin/orders" className="text-sm text-primary hover:underline">View all →</Link>
        </div>
        <div className="overflow-x-auto">
          <table className="w-full text-sm">
            <thead>
              <tr className="text-left text-muted-foreground border-b">
                <th className="pb-2 pr-3">#</th>
                <th className="pb-2 pr-3">Customer</th>
                <th className="pb-2 pr-3">Package</th>
                <th className="pb-2 pr-3">Amount</th>
                <th className="pb-2 pr-3">Status</th>
                <th className="pb-2">Date</th>
              </tr>
            </thead>
            <tbody>
              {data.recent.length === 0 && (
                <tr><td colSpan={6} className="py-6 text-center text-muted-foreground">No orders yet</td></tr>
              )}
              {data.recent.map((o: any) => (
                <tr key={o.id} className="border-b last:border-0">
                  <td className="py-3 pr-3 font-mono text-xs">#{String(o.order_number).padStart(4, "0")}</td>
                  <td className="py-3 pr-3">{o.customer_email}</td>
                  <td className="py-3 pr-3">{o.package_name} × {o.quantity}</td>
                  <td className="py-3 pr-3 font-medium">{formatBDT(o.total_bdt)}</td>
                  <td className="py-3 pr-3">
                    <span className={`px-2 py-0.5 rounded text-xs font-medium ${statusColor[o.status] ?? ""}`}>{o.status}</span>
                  </td>
                  <td className="py-3 text-muted-foreground text-xs">{new Date(o.created_at).toLocaleString()}</td>
                </tr>
              ))}
            </tbody>
          </table>
        </div>
      </Card>
    </div>
  );
}