import { createFileRoute, Link } from "@tanstack/react-router";
import { useState } from "react";
import { useQuery } from "@tanstack/react-query";
import { AdminShell, useIsAdmin } from "@/components/AdminShell";
import { fetchAllOrders, isSale } from "@/lib/adminData";
import { formatPrice, PRODUCTS as products } from "@/lib/products";
import { supabase } from "@/integrations/supabase/client";
import { useServerFn } from "@tanstack/react-start";
import { reconcilePayments } from "@/lib/orders.functions";

export const Route = createFileRoute("/_authenticated/dashboard")({
  head: () => ({
    meta: [
      { title: "Dashboard — Right On Gloss Admin" },
      { name: "description", content: "Sales and stock overview for Right On Gloss." },
      { property: "og:title", content: "Dashboard — Right On Gloss Admin" },
      { property: "og:description", content: "Sales and stock overview." },
      { property: "og:type", content: "website" },
      { name: "twitter:card", content: "summary" },
      { name: "robots", content: "noindex" },
    ],
  }),
  component: Dashboard,
});

function Dashboard() {
  const admin = useIsAdmin();
  const [paymentWarning, setPaymentWarning] = useState("");
  const reconcile = useServerFn(reconcilePayments);
  const orders = useQuery({ queryKey: ["admin-orders"], enabled: admin.data === true, queryFn: async () => {
    const result = await reconcile();
    setPaymentWarning(result.failed ? "Some payments could not be checked with Stripe. Verified sales are shown; payment checks will retry shortly." : "");
    return fetchAllOrders();
  }, refetchInterval: 60000 });
  const inv = useQuery({ queryKey: ["inventory"], enabled: admin.data === true, queryFn: async () => (await supabase.from("inventory").select("*")).data ?? [] });
  const pending = useQuery({ queryKey: ["pending-apps"], enabled: admin.data === true, queryFn: async () => (await supabase.from("wholesale_applications").select("id", { count: "exact", head: true }).eq("status", "pending")).count ?? 0 });

  const sales = (orders.data ?? []).filter(isSale);
  const now = Date.now();
  const last30 = sales.filter((o) => o.paid_at && now - new Date(o.paid_at).getTime() < 30 * 864e5);
  const revenue = sales.reduce((s, o) => s + o.total_kobo, 0);
  const units = sales.reduce((s, o) => s + o.units, 0);
  const retailRev = sales.filter((o) => o.kind === "Retail").reduce((s, o) => s + o.total_kobo, 0);
  const low = (inv.data ?? []).filter((i) => i.stock <= i.low_stock_threshold);

  const bySlug = new Map<string, number>();
  sales.forEach((o) => o.items.forEach((i) => bySlug.set(i.slug, (bySlug.get(i.slug) ?? 0) + i.units)));
  const top = products.map((p) => ({ p, units: bySlug.get(p.slug) ?? 0 })).sort((a, b) => b.units - a.units);
  const maxUnits = Math.max(1, ...top.map((t) => t.units));

  const Stat = ({ label, value, sub }: { label: string; value: string; sub?: string }) => (
    <div className="rounded-2xl bg-card p-5 shadow-sm">
      <p className="text-sm text-muted-foreground">{label}</p>
      <p className="mt-1 text-3xl font-semibold">{value}</p>
      {sub && <p className="mt-1 text-xs text-muted-foreground">{sub}</p>}
    </div>
  );

  return (
    <AdminShell title={<>Sales <em className="text-primary">dashboard</em></>}>
      {orders.isError && <p role="alert" className="mb-5 text-destructive">{orders.error.message}</p>}
      {paymentWarning && <p role="status" className="mb-5 text-muted-foreground">{paymentWarning}</p>}
      <div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-4">
        <Stat label="Verified live revenue" value={formatPrice(revenue)} sub={`Shop ${formatPrice(retailRev)} · Wholesale ${formatPrice(revenue - retailRev)}`} />
        <Stat label="Last 30 days" value={formatPrice(last30.reduce((s, o) => s + o.total_kobo, 0))} sub={`${last30.length} paid orders`} />
        <Stat label="Glosses sold" value={units.toLocaleString()} sub={`${sales.length} paid orders`} />
        <Stat label="Low-stock glosses" value={String(low.length)} sub={`${pending.data ?? 0} wholesale applications pending`} />
      </div>

      <div className="mt-8 grid gap-6 lg:grid-cols-2">
        <section className="rounded-2xl bg-card p-6">
          <h2 className="text-xl font-semibold">Best sellers</h2>
          <ul className="mt-4 space-y-3">
            {top.map(({ p, units }) => (
              <li key={p.slug}>
                <div className="flex justify-between text-sm"><span>{p.name}</span><span className="text-muted-foreground">{units} sold</span></div>
                <div className="mt-1 h-2 rounded-full bg-muted"><div className="h-2 rounded-full bg-primary" style={{ width: `${(units / maxUnits) * 100}%` }} /></div>
              </li>
            ))}
          </ul>
        </section>
        <section className="rounded-2xl bg-card p-6">
          <div className="flex items-center justify-between"><h2 className="text-xl font-semibold">Stock alerts</h2><Link to="/admin-inventory" className="text-sm font-semibold text-primary">Manage stock →</Link></div>
          {!low.length ? <p className="mt-4 text-muted-foreground">All glosses are well stocked.</p> : (
            <ul className="mt-4 space-y-2">
              {low.map((i) => (
                <li key={i.product_slug} className="flex justify-between rounded-xl bg-muted px-4 py-2 text-sm">
                  <span>{products.find((p) => p.slug === i.product_slug)?.name ?? i.product_slug}</span>
                  <span className="font-semibold text-destructive">{i.stock} left</span>
                </li>
              ))}
            </ul>
          )}
          <div className="mt-6 flex items-center justify-between"><h2 className="text-xl font-semibold">Recent orders</h2><Link to="/admin-orders" className="text-sm font-semibold text-primary">All orders →</Link></div>
          <ul className="mt-3 divide-y text-sm">
            {(orders.data ?? []).slice(0, 5).map((o) => (
              <li key={o.id} className="flex justify-between py-2"><span>{o.kind} · {new Date(o.created_at).toLocaleDateString()}</span><span className="capitalize text-muted-foreground">{o.status.replace("_", " ")} · {formatPrice(o.total_kobo)}</span></li>
            ))}
            {!orders.data?.length && <li className="py-2 text-muted-foreground">No orders yet.</li>}
          </ul>
        </section>
      </div>
    </AdminShell>
  );
}
