import { createFileRoute } from "@tanstack/react-router";
import { useState } from "react";
import { useQueryClient } from "@tanstack/react-query";
import { useParts } from "@/lib/queries";
import { supabase } from "@/integrations/supabase/client";
import { useAuth } from "@/lib/auth";
import { PageHeader } from "@/components/PageHeader";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogTrigger, DialogFooter } from "@/components/ui/dialog";
import { Package, Plus, Trash2, AlertTriangle } from "lucide-react";
import { toast } from "sonner";

export const Route = createFileRoute("/_authenticated/parts")({
  component: PartsPage,
});

function PartsPage() {
  const { user } = useAuth();
  const parts = useParts();
  const qc = useQueryClient();
  const [open, setOpen] = useState(false);
  const [form, setForm] = useState({ name: "", sku: "", quantity: "0", unit_cost: "0", min_stock: "0", location: "" });

  const submit = async (e: React.FormEvent) => {
    e.preventDefault();
    const { error } = await supabase.from("parts").insert({
      owner_id: user!.id,
      name: form.name,
      sku: form.sku || null,
      quantity: Number(form.quantity || 0),
      unit_cost: Number(form.unit_cost || 0),
      min_stock: Number(form.min_stock || 0),
      location: form.location || null,
    });
    if (error) return toast.error(error.message);
    toast.success("Part added");
    qc.invalidateQueries({ queryKey: ["parts"] });
    setOpen(false);
    setForm({ name: "", sku: "", quantity: "0", unit_cost: "0", min_stock: "0", location: "" });
  };

  const adjust = async (id: string, delta: number, current: number) => {
    const { error } = await supabase.from("parts").update({ quantity: Math.max(0, current + delta) }).eq("id", id);
    if (error) return toast.error(error.message);
    qc.invalidateQueries({ queryKey: ["parts"] });
  };
  const remove = async (id: string) => {
    const { error } = await supabase.from("parts").delete().eq("id", id);
    if (error) return toast.error(error.message);
    qc.invalidateQueries({ queryKey: ["parts"] });
  };

  return (
    <div>
      <PageHeader
        title="Parts inventory"
        actions={
          <Dialog open={open} onOpenChange={setOpen}>
            <DialogTrigger asChild><Button><Plus className="h-4 w-4" /> Add part</Button></DialogTrigger>
            <DialogContent>
              <DialogHeader><DialogTitle>Add part</DialogTitle></DialogHeader>
              <form onSubmit={submit} className="space-y-3">
                <div className="grid grid-cols-2 gap-3">
                  <div className="space-y-1.5"><Label>Name *</Label><Input required value={form.name} onChange={(e) => setForm({ ...form, name: e.target.value })} /></div>
                  <div className="space-y-1.5"><Label>SKU</Label><Input value={form.sku} onChange={(e) => setForm({ ...form, sku: e.target.value })} /></div>
                  <div className="space-y-1.5"><Label>Quantity</Label><Input type="number" value={form.quantity} onChange={(e) => setForm({ ...form, quantity: e.target.value })} /></div>
                  <div className="space-y-1.5"><Label>Unit cost</Label><Input type="number" step="0.01" value={form.unit_cost} onChange={(e) => setForm({ ...form, unit_cost: e.target.value })} /></div>
                  <div className="space-y-1.5"><Label>Min stock</Label><Input type="number" value={form.min_stock} onChange={(e) => setForm({ ...form, min_stock: e.target.value })} /></div>
                  <div className="space-y-1.5"><Label>Location</Label><Input value={form.location} onChange={(e) => setForm({ ...form, location: e.target.value })} /></div>
                </div>
                <DialogFooter><Button type="submit">Save</Button></DialogFooter>
              </form>
            </DialogContent>
          </Dialog>
        }
      />
      {(parts.data?.length ?? 0) === 0 ? (
        <div className="rounded-xl border border-dashed border-border bg-card p-12 text-center">
          <Package className="mx-auto h-10 w-10 text-muted-foreground" />
          <p className="mt-3 text-muted-foreground">No parts in inventory.</p>
        </div>
      ) : (
        <div className="overflow-hidden rounded-xl border border-border bg-card">
          <table className="w-full text-sm">
            <thead className="bg-secondary/40 text-left text-xs uppercase tracking-wider text-muted-foreground">
              <tr>
                <th className="px-4 py-3">Part</th><th className="px-4 py-3">SKU</th>
                <th className="px-4 py-3">Location</th><th className="px-4 py-3 text-right">Unit cost</th>
                <th className="px-4 py-3 text-center">Quantity</th><th />
              </tr>
            </thead>
            <tbody>
              {parts.data!.map((p) => {
                const low = p.quantity <= p.min_stock;
                return (
                  <tr key={p.id} className="border-t border-border">
                    <td className="px-4 py-3 font-medium">
                      <div className="flex items-center gap-2">
                        {p.name}
                        {low && <AlertTriangle className="h-3.5 w-3.5 text-warning" />}
                      </div>
                    </td>
                    <td className="px-4 py-3 font-mono text-xs text-muted-foreground">{p.sku ?? "—"}</td>
                    <td className="px-4 py-3 text-muted-foreground">{p.location ?? "—"}</td>
                    <td className="px-4 py-3 text-right font-mono">${Number(p.unit_cost).toFixed(2)}</td>
                    <td className="px-4 py-3">
                      <div className="flex items-center justify-center gap-1">
                        <Button size="sm" variant="outline" className="h-7 w-7 p-0" onClick={() => adjust(p.id, -1, p.quantity)}>-</Button>
                        <span className={`w-10 text-center font-mono ${low ? "text-warning" : ""}`}>{p.quantity}</span>
                        <Button size="sm" variant="outline" className="h-7 w-7 p-0" onClick={() => adjust(p.id, 1, p.quantity)}>+</Button>
                      </div>
                    </td>
                    <td className="px-4 py-3 text-right"><Button size="sm" variant="ghost" onClick={() => remove(p.id)}><Trash2 className="h-4 w-4" /></Button></td>
                  </tr>
                );
              })}
            </tbody>
          </table>
        </div>
      )}
    </div>
  );
}
