import { createFileRoute } from "@tanstack/react-router";
import { RequireRole } from "@/hooks/use-roles";
import { useMutation, useQuery, useQueryClient } from "@tanstack/react-query";
import { useMemo, useState } from "react";
import { supabase } from "@/integrations/supabase/client";
import { Button } from "@/components/ui/button";
import { Card, CardContent, CardHeader, CardTitle } from "@/components/ui/card";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Textarea } from "@/components/ui/textarea";
import { Badge } from "@/components/ui/badge";
import { Table, TableBody, TableCell, TableHead, TableHeader, TableRow } from "@/components/ui/table";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { Dialog, DialogContent, DialogFooter, DialogHeader, DialogTitle, DialogTrigger } from "@/components/ui/dialog";
import { Package, Plus, Pencil, Trash2, Search } from "lucide-react";
import { toast } from "sonner";

export const Route = createFileRoute("/_authenticated/inventory")({
  component: () => (
    <RequireRole any={["super_admin","admin","company_admin","ops_manager","supervisor"]}>
      <InventoryPage />
    </RequireRole>
  ),
});

type Item = {
  id: string;
  name: string;
  category: string;
  serial_number: string | null;
  quantity: number;
  condition: "new" | "good" | "fair" | "poor" | "damaged";
  status: "available" | "assigned" | "maintenance" | "lost" | "retired";
  assigned_guard_id: string | null;
  purchase_date: string | null;
  notes: string | null;
};

const CATEGORIES = ["uniform", "footwear", "radio", "torch", "baton", "whistle", "raincoat", "belt", "cap", "id_card", "other"];
const CONDITIONS = ["new", "good", "fair", "poor", "damaged"] as const;
const STATUSES = ["available", "assigned", "maintenance", "lost", "retired"] as const;

type FormState = {
  name: string; category: string; serial_number: string; quantity: string;
  condition: Item["condition"]; status: Item["status"];
  assigned_guard_id: string; purchase_date: string; notes: string;
};
const empty: FormState = {
  name: "", category: "uniform", serial_number: "", quantity: "1",
  condition: "good", status: "available",
  assigned_guard_id: "", purchase_date: "", notes: "",
};

function InventoryPage() {
  const qc = useQueryClient();
  const [q, setQ] = useState("");
  const [open, setOpen] = useState(false);
  const [editing, setEditing] = useState<Item | null>(null);
  const [form, setForm] = useState<FormState>(empty);

  const { data = [], isLoading } = useQuery({
    queryKey: ["inventory"],
    queryFn: async () => {
      const { data, error } = await supabase
        .from("inventory_items").select("*").order("created_at", { ascending: false });
      if (error) throw error;
      return data as Item[];
    },
  });

  const { data: guards = [] } = useQuery({
    queryKey: ["guards-min"],
    queryFn: async () => {
      const { data, error } = await supabase
        .from("security_guards").select("id, full_name, employee_id").order("full_name");
      if (error) throw error;
      return data as { id: string; full_name: string; employee_id: string }[];
    },
  });

  const filtered = useMemo(() => {
    const s = q.toLowerCase();
    return data.filter((i) =>
      [i.name, i.category, i.serial_number ?? "", i.status, i.condition]
        .join(" ").toLowerCase().includes(s),
    );
  }, [data, q]);

  const save = useMutation({
    mutationFn: async () => {
      const payload = {
        name: form.name.trim(),
        category: form.category,
        serial_number: form.serial_number.trim() || null,
        quantity: Number(form.quantity) || 1,
        condition: form.condition,
        status: form.status,
        assigned_guard_id: form.assigned_guard_id || null,
        purchase_date: form.purchase_date || null,
        notes: form.notes.trim() || null,
      };
      if (!payload.name) throw new Error("Name required");
      if (editing) {
        const { error } = await supabase.from("inventory_items").update(payload).eq("id", editing.id);
        if (error) throw error;
      } else {
        const { error } = await supabase.from("inventory_items").insert(payload);
        if (error) throw error;
      }
    },
    onSuccess: () => {
      toast.success(editing ? "Item updated" : "Item added");
      setOpen(false); setEditing(null); setForm(empty);
      qc.invalidateQueries({ queryKey: ["inventory"] });
    },
    onError: (e: Error) => toast.error(e.message),
  });

  const del = useMutation({
    mutationFn: async (id: string) => {
      const { error } = await supabase.from("inventory_items").delete().eq("id", id);
      if (error) throw error;
    },
    onSuccess: () => {
      toast.success("Deleted");
      qc.invalidateQueries({ queryKey: ["inventory"] });
    },
    onError: (e: Error) => toast.error(e.message),
  });

  const openNew = () => { setEditing(null); setForm(empty); setOpen(true); };
  const openEdit = (i: Item) => {
    setEditing(i);
    setForm({
      name: i.name, category: i.category, serial_number: i.serial_number ?? "",
      quantity: String(i.quantity), condition: i.condition, status: i.status,
      assigned_guard_id: i.assigned_guard_id ?? "",
      purchase_date: i.purchase_date ?? "", notes: i.notes ?? "",
    });
    setOpen(true);
  };

  return (
    <div className="space-y-4">
      <div className="flex items-center justify-between gap-2 flex-wrap">
        <div>
          <h1 className="text-2xl font-bold flex items-center gap-2"><Package className="h-6 w-6" /> Uniform & Equipment Inventory</h1>
          <p className="text-sm text-muted-foreground">Track uniforms, gear, and equipment assigned to guards.</p>
        </div>
        <Dialog open={open} onOpenChange={(o) => { setOpen(o); if (!o) { setEditing(null); setForm(empty); } }}>
          <DialogTrigger asChild>
            <Button onClick={openNew}><Plus className="h-4 w-4 mr-1" /> Add Item</Button>
          </DialogTrigger>
          <DialogContent className="max-w-lg">
            <DialogHeader><DialogTitle>{editing ? "Edit Item" : "Add Item"}</DialogTitle></DialogHeader>
            <div className="grid gap-3">
              <div><Label>Name</Label><Input value={form.name} onChange={(e) => setForm({ ...form, name: e.target.value })} /></div>
              <div className="grid grid-cols-2 gap-3">
                <div>
                  <Label>Category</Label>
                  <Select value={form.category} onValueChange={(v) => setForm({ ...form, category: v })}>
                    <SelectTrigger><SelectValue /></SelectTrigger>
                    <SelectContent>{CATEGORIES.map((c) => <SelectItem key={c} value={c}>{c}</SelectItem>)}</SelectContent>
                  </Select>
                </div>
                <div><Label>Quantity</Label><Input type="number" min={1} value={form.quantity} onChange={(e) => setForm({ ...form, quantity: e.target.value })} /></div>
              </div>
              <div className="grid grid-cols-2 gap-3">
                <div>
                  <Label>Condition</Label>
                  <Select value={form.condition} onValueChange={(v) => setForm({ ...form, condition: v as typeof form.condition })}>
                    <SelectTrigger><SelectValue /></SelectTrigger>
                    <SelectContent>{CONDITIONS.map((c) => <SelectItem key={c} value={c}>{c}</SelectItem>)}</SelectContent>
                  </Select>
                </div>
                <div>
                  <Label>Status</Label>
                  <Select value={form.status} onValueChange={(v) => setForm({ ...form, status: v as typeof form.status })}>
                    <SelectTrigger><SelectValue /></SelectTrigger>
                    <SelectContent>{STATUSES.map((s) => <SelectItem key={s} value={s}>{s}</SelectItem>)}</SelectContent>
                  </Select>
                </div>
              </div>
              <div><Label>Serial Number</Label><Input value={form.serial_number} onChange={(e) => setForm({ ...form, serial_number: e.target.value })} /></div>
              <div>
                <Label>Assigned Guard</Label>
                <Select value={form.assigned_guard_id || "none"} onValueChange={(v) => setForm({ ...form, assigned_guard_id: v === "none" ? "" : v })}>
                  <SelectTrigger><SelectValue placeholder="Unassigned" /></SelectTrigger>
                  <SelectContent>
                    <SelectItem value="none">Unassigned</SelectItem>
                    {guards.map((g) => <SelectItem key={g.id} value={g.id}>{g.full_name} ({g.employee_id})</SelectItem>)}
                  </SelectContent>
                </Select>
              </div>
              <div><Label>Purchase Date</Label><Input type="date" value={form.purchase_date} onChange={(e) => setForm({ ...form, purchase_date: e.target.value })} /></div>
              <div><Label>Notes</Label><Textarea value={form.notes} onChange={(e) => setForm({ ...form, notes: e.target.value })} /></div>
            </div>
            <DialogFooter>
              <Button variant="outline" onClick={() => setOpen(false)}>Cancel</Button>
              <Button onClick={() => save.mutate()} disabled={save.isPending}>{editing ? "Update" : "Save"}</Button>
            </DialogFooter>
          </DialogContent>
        </Dialog>
      </div>

      <Card>
        <CardHeader>
          <CardTitle className="flex items-center justify-between gap-2">
            <span>Items ({filtered.length})</span>
            <div className="relative w-64">
              <Search className="h-4 w-4 absolute left-2 top-2.5 text-muted-foreground" />
              <Input className="pl-8" placeholder="Search…" value={q} onChange={(e) => setQ(e.target.value)} />
            </div>
          </CardTitle>
        </CardHeader>
        <CardContent>
          {isLoading ? <p className="text-muted-foreground">Loading…</p> : (
            <div className="overflow-x-auto">
              <Table>
                <TableHeader>
                  <TableRow>
                    <TableHead>Name</TableHead><TableHead>Category</TableHead><TableHead>Qty</TableHead>
                    <TableHead>Serial</TableHead><TableHead>Condition</TableHead><TableHead>Status</TableHead>
                    <TableHead>Assigned</TableHead><TableHead className="text-right">Actions</TableHead>
                  </TableRow>
                </TableHeader>
                <TableBody>
                  {filtered.map((i) => {
                    const g = guards.find((x) => x.id === i.assigned_guard_id);
                    return (
                      <TableRow key={i.id}>
                        <TableCell className="font-medium">{i.name}</TableCell>
                        <TableCell>{i.category}</TableCell>
                        <TableCell>{i.quantity}</TableCell>
                        <TableCell className="text-muted-foreground">{i.serial_number ?? "—"}</TableCell>
                        <TableCell><Badge variant="outline">{i.condition}</Badge></TableCell>
                        <TableCell><Badge>{i.status}</Badge></TableCell>
                        <TableCell>{g ? g.full_name : "—"}</TableCell>
                        <TableCell className="text-right space-x-1">
                          <Button size="icon" variant="ghost" onClick={() => openEdit(i)}><Pencil className="h-4 w-4" /></Button>
                          <Button size="icon" variant="ghost" onClick={() => { if (confirm("Delete this item?")) del.mutate(i.id); }}><Trash2 className="h-4 w-4" /></Button>
                        </TableCell>
                      </TableRow>
                    );
                  })}
                  {filtered.length === 0 && (
                    <TableRow><TableCell colSpan={8} className="text-center text-muted-foreground py-8">No items</TableCell></TableRow>
                  )}
                </TableBody>
              </Table>
            </div>
          )}
        </CardContent>
      </Card>
    </div>
  );
}