import { createFileRoute } from "@tanstack/react-router";
import { useQuery, useQueryClient, useMutation } from "@tanstack/react-query";
import { useServerFn } from "@tanstack/react-start";
import { listPackages, upsertPackage, deletePackage } from "@/lib/admin.functions";
import { Card } from "@/components/ui/card";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Label } from "@/components/ui/label";
import { Textarea } from "@/components/ui/textarea";
import { Switch } from "@/components/ui/switch";
import { Dialog, DialogContent, DialogHeader, DialogTitle, DialogTrigger, DialogFooter } from "@/components/ui/dialog";
import { formatBDT } from "@/lib/format";
import { useState } from "react";
import { toast } from "sonner";
import { Pencil, Trash2, Plus } from "lucide-react";

export const Route = createFileRoute("/admin/packages")({
  component: PackagesPage,
});

type Pkg = { id?: string; name: string; credits: number; price_bdt: number; description?: string | null; is_active: boolean; sort_order: number };
const empty: Pkg = { name: "", credits: 205, price_bdt: 0, description: "", is_active: true, sort_order: 0 };

function PackagesPage() {
  const listFn = useServerFn(listPackages);
  const upsertFn = useServerFn(upsertPackage);
  const delFn = useServerFn(deletePackage);
  const qc = useQueryClient();
  const { data, isLoading } = useQuery({ queryKey: ["admin", "packages"], queryFn: () => listFn() });
  const [open, setOpen] = useState(false);
  const [editing, setEditing] = useState<Pkg>(empty);

  const save = useMutation({
    mutationFn: (p: Pkg) => upsertFn({ data: p as any }),
    onSuccess: () => { qc.invalidateQueries({ queryKey: ["admin", "packages"] }); toast.success("Saved"); setOpen(false); },
    onError: (e: any) => toast.error(e.message ?? "Failed"),
  });
  const del = useMutation({
    mutationFn: (id: string) => delFn({ data: { id } }),
    onSuccess: () => { qc.invalidateQueries({ queryKey: ["admin", "packages"] }); toast.success("Deleted"); },
    onError: (e: any) => toast.error(e.message ?? "Failed"),
  });

  const openNew = () => { setEditing(empty); setOpen(true); };
  const openEdit = (p: any) => { setEditing({ ...p }); setOpen(true); };

  return (
    <div className="space-y-4">
      <div className="flex justify-between items-center">
        <h2 className="text-lg font-semibold">Packages</h2>
        <Button onClick={openNew}><Plus className="w-4 h-4" /> Add Package</Button>
      </div>

      <Card className="p-0 overflow-hidden">
        <table className="w-full text-sm">
          <thead className="bg-muted/50 text-left">
            <tr><th className="p-3">Name</th><th className="p-3">Credits</th><th className="p-3">Price</th><th className="p-3">Active</th><th className="p-3">Sort</th><th className="p-3 text-right">Actions</th></tr>
          </thead>
          <tbody>
            {isLoading && <tr><td colSpan={6} className="p-6 text-center text-muted-foreground">Loading...</td></tr>}
            {!isLoading && data?.length === 0 && <tr><td colSpan={6} className="p-6 text-center text-muted-foreground">No packages</td></tr>}
            {data?.map((p: any) => (
              <tr key={p.id} className="border-t">
                <td className="p-3 font-medium">{p.name}</td>
                <td className="p-3">{p.credits}</td>
                <td className="p-3">{formatBDT(p.price_bdt)}</td>
                <td className="p-3">{p.is_active ? "✅" : "—"}</td>
                <td className="p-3">{p.sort_order}</td>
                <td className="p-3 text-right">
                  <Button size="sm" variant="ghost" onClick={() => openEdit(p)}><Pencil className="w-3 h-3" /></Button>
                  <Button size="sm" variant="ghost" onClick={() => confirm("Delete this package?") && del.mutate(p.id)}><Trash2 className="w-3 h-3 text-red-600" /></Button>
                </td>
              </tr>
            ))}
          </tbody>
        </table>
      </Card>

      <Dialog open={open} onOpenChange={setOpen}>
        <DialogContent>
          <DialogHeader><DialogTitle>{editing.id ? "Edit" : "New"} Package</DialogTitle></DialogHeader>
          <div className="space-y-3">
            <div><Label>Name</Label><Input value={editing.name} onChange={(e) => setEditing({ ...editing, name: e.target.value })} /></div>
            <div className="grid grid-cols-2 gap-3">
              <div><Label>Credits</Label><Input type="number" value={editing.credits} onChange={(e) => setEditing({ ...editing, credits: +e.target.value })} /></div>
              <div><Label>Price (BDT)</Label><Input type="number" value={editing.price_bdt} onChange={(e) => setEditing({ ...editing, price_bdt: +e.target.value })} /></div>
            </div>
            <div><Label>Description</Label><Textarea value={editing.description ?? ""} onChange={(e) => setEditing({ ...editing, description: e.target.value })} /></div>
            <div className="grid grid-cols-2 gap-3 items-end">
              <div><Label>Sort Order</Label><Input type="number" value={editing.sort_order} onChange={(e) => setEditing({ ...editing, sort_order: +e.target.value })} /></div>
              <div className="flex items-center gap-2"><Switch checked={editing.is_active} onCheckedChange={(v) => setEditing({ ...editing, is_active: v })} /> <Label>Active</Label></div>
            </div>
          </div>
          <DialogFooter>
            <Button variant="outline" onClick={() => setOpen(false)}>Cancel</Button>
            <Button onClick={() => save.mutate(editing)} disabled={save.isPending}>Save</Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  );
}