import { createFileRoute } from "@tanstack/react-router";
import { RequireRole } from "@/hooks/use-roles";
import { useQuery, useMutation, 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 { Tabs, TabsContent, TabsList, TabsTrigger } from "@/components/ui/tabs";
import { Badge } from "@/components/ui/badge";
import { Download, Printer, Plus, Trash2, QrCode } from "lucide-react";
import { toast } from "sonner";

export const Route = createFileRoute("/_authenticated/qr-management")({
  component: () => (<RequireRole any={["super_admin","admin","company_admin","ops_manager"]}><QrManagement /></RequireRole>),
});

const qrUrl = (data: string, size = 240) =>
  `https://api.qrserver.com/v1/create-qr-code/?size=${size}x${size}&margin=2&data=${encodeURIComponent(data)}`;

function QrManagement() {
  const qc = useQueryClient();
  const { data: guards, isLoading } = useQuery({
    queryKey: ["guards"],
    queryFn: async () => {
      const { data, error } = await supabase
        .from("security_guards")
        .select("id, employee_id, full_name, status")
        .order("employee_id");
      if (error) throw error;
      return data;
    },
  });

  const [q, setQ] = useState("");
  const [postName, setPostName] = useState("");
  const [postNotes, setPostNotes] = useState("");

  const { data: posts = [], isLoading: postsLoading } = useQuery({
    queryKey: ["qr_posts"],
    queryFn: async () => {
      const { data, error } = await supabase
        .from("qr_posts")
        .select("id, name, payload, notes")
        .order("name");
      if (error) throw error;
      return data;
    },
  });

  const addPostMut = useMutation({
    mutationFn: async (input: { name: string; notes: string }) => {
      const payload = `POST:${input.name}`;
      const { error } = await supabase.from("qr_posts").insert({
        name: input.name, payload, notes: input.notes || null,
      });
      if (error) throw error;
    },
    onSuccess: () => {
      toast.success("Post QR added");
      setPostName(""); setPostNotes("");
      qc.invalidateQueries({ queryKey: ["qr_posts"] });
    },
    onError: (e: Error) => toast.error(e.message),
  });

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

  const filteredGuards = useMemo(() => {
    const term = q.trim().toLowerCase();
    const rows = guards ?? [];
    if (!term) return rows;
    return rows.filter((g) =>
      [g.employee_id, g.full_name].some((v) => (v ?? "").toString().toLowerCase().includes(term)),
    );
  }, [guards, q]);

  const addPost = () => {
    const name = postName.trim();
    if (!name) return toast.error("Enter a post name");
    if (posts.some((p) => p.name.toLowerCase() === name.toLowerCase())) {
      return toast.error("Post already exists");
    }
    addPostMut.mutate({ name, notes: postNotes.trim() });
  };

  const removePost = (id: string) => {
    removePostMut.mutate(id);
  };

  const downloadQr = async (payload: string, filename: string) => {
    try {
      const res = await fetch(qrUrl(payload, 512));
      const blob = await res.blob();
      const url = URL.createObjectURL(blob);
      const a = document.createElement("a");
      a.href = url;
      a.download = `${filename}.png`;
      a.click();
      URL.revokeObjectURL(url);
    } catch {
      toast.error("Download failed");
    }
  };

  const printAll = (items: { title: string; subtitle: string; payload: string }[]) => {
    if (!items.length) return toast.error("Nothing to print");
    const html = `<!doctype html><html><head><title>QR Codes</title>
      <style>
        body{font-family:system-ui,sans-serif;margin:24px}
        .grid{display:grid;grid-template-columns:repeat(3,1fr);gap:16px}
        .card{border:1px solid #ddd;border-radius:8px;padding:12px;text-align:center;break-inside:avoid}
        .card img{width:100%;height:auto}
        .t{font-weight:600;margin-top:6px}
        .s{color:#666;font-size:12px;font-family:ui-monospace,monospace}
        @media print{ .no-print{display:none} }
      </style></head><body>
      <div class="no-print" style="margin-bottom:12px"><button onclick="window.print()">Print</button></div>
      <div class="grid">
        ${items.map((i) => `<div class="card">
          <img src="${qrUrl(i.payload, 360)}" alt="" />
          <div class="t">${i.title}</div>
          <div class="s">${i.subtitle}</div>
        </div>`).join("")}
      </div></body></html>`;
    const w = window.open("", "_blank");
    if (!w) return toast.error("Allow popups to print");
    w.document.write(html);
    w.document.close();
  };

  return (
    <div className="space-y-6">
      <div>
        <h1 className="text-3xl font-bold tracking-tight flex items-center gap-2">
          <QrCode className="h-7 w-7 text-primary" /> QR Management
        </h1>
        <p className="text-muted-foreground">Generate, print and download QR codes for guards and posts</p>
      </div>

      <Tabs defaultValue="guards">
        <TabsList>
          <TabsTrigger value="guards">Guard QR</TabsTrigger>
          <TabsTrigger value="posts">Post / Location QR</TabsTrigger>
        </TabsList>

        <TabsContent value="guards" className="space-y-4">
          <div className="flex flex-col sm:flex-row gap-2 justify-between">
            <Input placeholder="Search by employee ID or name…" value={q} onChange={(e) => setQ(e.target.value)} className="max-w-md" />
            <Button variant="outline" onClick={() => printAll(filteredGuards.map((g) => ({
              title: g.full_name, subtitle: g.employee_id, payload: `GUARD:${g.employee_id}`,
            })))}>
              <Printer className="h-4 w-4 mr-1" /> Print all ({filteredGuards.length})
            </Button>
          </div>

          {isLoading ? (
            <p className="text-muted-foreground">Loading…</p>
          ) : filteredGuards.length === 0 ? (
            <Card><CardContent className="py-10 text-center text-muted-foreground">No guards found.</CardContent></Card>
          ) : (
            <div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-3">
              {filteredGuards.map((g) => {
                const payload = `GUARD:${g.employee_id}`;
                return (
                  <Card key={g.id}>
                    <CardHeader className="pb-2">
                      <div className="flex items-start justify-between">
                        <div>
                          <CardTitle className="text-base">{g.full_name}</CardTitle>
                          <p className="text-xs font-mono text-muted-foreground">{g.employee_id}</p>
                        </div>
                        <Badge variant={g.status === "active" ? "default" : "secondary"}>{g.status}</Badge>
                      </div>
                    </CardHeader>
                    <CardContent className="space-y-3">
                      <div className="bg-white rounded-md p-3 flex items-center justify-center border">
                        <img src={qrUrl(payload)} alt={`QR for ${g.employee_id}`} className="w-44 h-44" />
                      </div>
                      <div className="flex gap-2">
                        <Button size="sm" variant="outline" className="flex-1"
                          onClick={() => downloadQr(payload, `guard-${g.employee_id}`)}>
                          <Download className="h-4 w-4 mr-1" /> PNG
                        </Button>
                        <Button size="sm" variant="outline" className="flex-1"
                          onClick={() => printAll([{ title: g.full_name, subtitle: g.employee_id, payload }])}>
                          <Printer className="h-4 w-4 mr-1" /> Print
                        </Button>
                      </div>
                    </CardContent>
                  </Card>
                );
              })}
            </div>
          )}
        </TabsContent>

        <TabsContent value="posts" className="space-y-4">
          <Card>
            <CardHeader><CardTitle className="text-base">Add a post / location</CardTitle></CardHeader>
            <CardContent>
              <div className="grid gap-2 sm:grid-cols-[1fr_1fr_auto]">
                <div className="space-y-1">
                  <Label htmlFor="post">Post name</Label>
                  <Input id="post" placeholder="e.g. Main Gate" value={postName}
                    onChange={(e) => setPostName(e.target.value)}
                    onKeyDown={(e) => { if (e.key === "Enter") addPost(); }} />
                </div>
                <div className="space-y-1">
                  <Label htmlFor="notes">Notes (optional)</Label>
                  <Input id="notes" placeholder="Building / floor / details" value={postNotes}
                    onChange={(e) => setPostNotes(e.target.value)} />
                </div>
                <Button onClick={addPost} disabled={addPostMut.isPending} className="sm:self-end">
                  <Plus className="h-4 w-4 mr-1" /> {addPostMut.isPending ? "Adding…" : "Add"}
                </Button>
              </div>
              <p className="text-xs text-muted-foreground mt-2">Shared with your team. Payload format: <code>POST:&lt;name&gt;</code></p>
            </CardContent>
          </Card>

          {posts.length > 0 && (
            <div className="flex justify-end">
              <Button variant="outline" onClick={() => printAll(posts.map((p) => ({
                title: p.name, subtitle: p.payload, payload: p.payload,
              })))}>
                <Printer className="h-4 w-4 mr-1" /> Print all ({posts.length})
              </Button>
            </div>
          )}

          {postsLoading ? (
            <p className="text-muted-foreground">Loading…</p>
          ) : posts.length === 0 ? (
            <Card><CardContent className="py-10 text-center text-muted-foreground">No post QR codes yet.</CardContent></Card>
          ) : (
            <div className="grid gap-4 sm:grid-cols-2 lg:grid-cols-3">
              {posts.map((p) => (
                <Card key={p.id}>
                  <CardHeader className="pb-2 flex flex-row items-start justify-between">
                    <div>
                      <CardTitle className="text-base">{p.name}</CardTitle>
                      <p className="text-xs font-mono text-muted-foreground">{p.payload}</p>
                      {p.notes && <p className="text-xs text-muted-foreground mt-1">{p.notes}</p>}
                    </div>
                    <Button size="icon" variant="ghost" onClick={() => removePost(p.id)}>
                      <Trash2 className="h-4 w-4 text-destructive" />
                    </Button>
                  </CardHeader>
                  <CardContent className="space-y-3">
                    <div className="bg-white rounded-md p-3 flex items-center justify-center border">
                      <img src={qrUrl(p.payload)} alt={`QR for ${p.name}`} className="w-44 h-44" />
                    </div>
                    <div className="flex gap-2">
                      <Button size="sm" variant="outline" className="flex-1"
                        onClick={() => downloadQr(p.payload, `post-${p.name}`)}>
                        <Download className="h-4 w-4 mr-1" /> PNG
                      </Button>
                      <Button size="sm" variant="outline" className="flex-1"
                        onClick={() => printAll([{ title: p.name, subtitle: p.payload, payload: p.payload }])}>
                        <Printer className="h-4 w-4 mr-1" /> Print
                      </Button>
                    </div>
                  </CardContent>
                </Card>
              ))}
            </div>
          )}
        </TabsContent>
      </Tabs>
    </div>
  );
}