import { createFileRoute } from "@tanstack/react-router";
import { useQuery, useQueryClient } from "@tanstack/react-query";
import { useState } from "react";
import { toast } from "sonner";
import { AdminShell, useIsAdmin } from "@/components/AdminShell";
import { PRODUCTS as products } from "@/lib/products";
import { supabase } from "@/integrations/supabase/client";

export const Route = createFileRoute("/_authenticated/admin-inventory")({
  head: () => ({
    meta: [
      { title: "Inventory — Right On Gloss Admin" },
      { name: "description", content: "Track and update Right On Gloss stock levels." },
      { property: "og:title", content: "Inventory — Right On Gloss Admin" },
      { property: "og:description", content: "Stock levels per gloss." },
      { name: "robots", content: "noindex" },
      { property: "og:type", content: "website" },
      { name: "twitter:card", content: "summary" },
    ],
  }),
  component: Inventory,
});

function Inventory() {
  const admin = useIsAdmin();
  const qc = useQueryClient();
  const inv = useQuery({ queryKey: ["inventory"], enabled: admin.data === true, queryFn: async () => (await supabase.from("inventory").select("*")).data ?? [] });
  const [edits, setEdits] = useState<Record<string, { stock?: string; threshold?: string; add?: string }>>({});

  const save = async (slug: string, current: { stock: number; low_stock_threshold: number } | undefined) => {
    const e = edits[slug] ?? {};
    let stock = e.stock !== undefined && e.stock !== "" ? Number(e.stock) : current?.stock ?? 0;
    if (e.add) stock += Number(e.add);
    const threshold = e.threshold !== undefined && e.threshold !== "" ? Number(e.threshold) : current?.low_stock_threshold ?? 24;
    if (!Number.isFinite(stock) || stock < 0 || !Number.isFinite(threshold) || threshold < 0) { toast.error("Enter whole numbers of 0 or more."); return; }
    const { error } = await supabase.from("inventory").upsert({ product_slug: slug, stock: Math.floor(stock), low_stock_threshold: Math.floor(threshold), updated_at: new Date().toISOString() });
    if (error) { toast.error("Couldn't save stock."); return; }
    toast.success("Stock updated");
    setEdits((x) => ({ ...x, [slug]: {} }));
    qc.invalidateQueries({ queryKey: ["inventory"] });
  };

  return (
    <AdminShell title={<>Stock <em className="text-primary">inventory</em></>}>
      <p className="text-muted-foreground">Stock drops automatically when a shop or wholesale order is paid (a wholesale box = 12 glosses). Add new deliveries here.</p>
      <div className="mt-6 overflow-x-auto rounded-2xl bg-card">
        <table className="w-full text-sm">
          <thead><tr className="border-b text-left text-muted-foreground"><th className="p-4">Gloss</th><th className="p-4">In stock</th><th className="p-4">Set stock to</th><th className="p-4">Add delivery</th><th className="p-4">Low-stock alert at</th><th className="p-4" /></tr></thead>
          <tbody>
            {products.map((p) => {
              const row = inv.data?.find((i) => i.product_slug === p.slug);
              const e = edits[p.slug] ?? {};
              const low = row ? row.stock <= row.low_stock_threshold : true;
              const set = (k: "stock" | "threshold" | "add", v: string) => setEdits((x) => ({ ...x, [p.slug]: { ...x[p.slug], [k]: v } }));
              return (
                <tr key={p.slug} className="border-b last:border-0">
                  <td className="p-4"><div className="flex items-center gap-3"><img src={p.image} alt="" className="h-10 w-10 rounded-lg object-cover" />{p.name}</div></td>
                  <td className={`p-4 font-semibold ${low ? "text-destructive" : ""}`}>{row?.stock ?? 0}{low && " · low"}</td>
                  <td className="p-4"><input type="number" min={0} value={e.stock ?? ""} onChange={(ev) => set("stock", ev.target.value)} placeholder={String(row?.stock ?? 0)} className="w-24 rounded-lg border bg-background px-2 py-1" /></td>
                  <td className="p-4"><input type="number" min={0} value={e.add ?? ""} onChange={(ev) => set("add", ev.target.value)} placeholder="+0" className="w-24 rounded-lg border bg-background px-2 py-1" /></td>
                  <td className="p-4"><input type="number" min={0} value={e.threshold ?? ""} onChange={(ev) => set("threshold", ev.target.value)} placeholder={String(row?.low_stock_threshold ?? 24)} className="w-24 rounded-lg border bg-background px-2 py-1" /></td>
                  <td className="p-4"><button onClick={() => save(p.slug, row)} className="btn-gloss px-4 py-1.5 text-sm">Save</button></td>
                </tr>
              );
            })}
          </tbody>
        </table>
      </div>
    </AdminShell>
  );
}
