import { createFileRoute } from "@tanstack/react-router";
import { useMemo, useState } from "react";
import { PageHeader } from "@/components/common/PageHeader";
import { AdminDataTable, type Column } from "@/components/common/AdminDataTable";
import { StatCard } from "@/components/common/StatCard";
import { Button } from "@/components/ui/button";
import { Input } from "@/components/ui/input";
import { Dialog, DialogTrigger, DialogContent, DialogHeader, DialogTitle, DialogFooter } from "@/components/ui/dialog";
import { Label } from "@/components/ui/label";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { players } from "@/features/_mock/data";
import { formatGEL, formatWGC, LariMark, WGCMark } from "@/lib/currency";
import { toast } from "sonner";
import { Coins, Plus, Minus } from "lucide-react";

export const Route = createFileRoute("/admin/balances")({
  head: () => ({ meta: [{ title: "Balances — Admin" }, { name: "description", content: "Adjust GEL balances and WGC coins for players." }] }),
  component: AdminBalancesPage,
});

type Row = { id: string; name: string; gel: number; wgc: number; last: string };
const rows: Row[] = players.slice(0, 20).map((p, i) => ({
  id: p.id, name: p.name,
  gel: +((i * 12.34) % 300 + 4.99).toFixed(2),
  wgc: 200 + (i * 137) % 4800,
  last: p.lastSeen,
}));

function AdminBalancesPage() {
  const [q, setQ] = useState("");
  const [selected, setSelected] = useState<Row | null>(null);
  const [op, setOp] = useState<"credit" | "debit">("credit");
  const [amt, setAmt] = useState("10");
  const [cur, setCur] = useState<"GEL" | "WGC">("GEL");
  const [reason, setReason] = useState("");

  const filtered = useMemo(() => rows.filter((r) => q === "" || r.name.toLowerCase().includes(q.toLowerCase()) || r.id.includes(q)), [q]);
  const totalGel = rows.reduce((a, b) => a + b.gel, 0);
  const totalWgc = rows.reduce((a, b) => a + b.wgc, 0);

  const cols: Column<Row>[] = [
    { key: "u", header: "User", cell: (r) => <span className="font-medium">{r.name}</span> },
    { key: "id", header: "ID", cell: (r) => <span className="font-mono text-xs">{r.id}</span> },
    { key: "g", header: "GEL", cell: (r) => <span className="inline-flex items-center gap-1 font-mono"><LariMark className="h-3.5 w-3.5" /> {r.gel.toFixed(2)}</span> },
    { key: "w", header: "WGC", cell: (r) => <span className="inline-flex items-center gap-1 font-mono"><WGCMark className="h-3.5 w-3.5" /> {r.wgc.toLocaleString()}</span> },
    { key: "l", header: "Last seen", cell: (r) => <span className="text-muted-foreground">{r.last}</span> },
  ];

  return (
    <div>
      <PageHeader title="Balances" description="Credit or debit user balances and coins." />
      <div className="mb-4 grid grid-cols-2 gap-3 md:grid-cols-3">
        <StatCard label="Total GEL held" value={formatGEL(totalGel)} tone="primary" icon={<Coins className="h-4 w-4" />} />
        <StatCard label="Total WGC held" value={formatWGC(totalWgc)} tone="primary" icon={<Coins className="h-4 w-4" />} />
        <StatCard label="Wallets" value={rows.length} />
      </div>
      <AdminDataTable
        rows={filtered} columns={cols} search={q} onSearchChange={setQ}
        rowActions={(r) => (
          <div className="flex justify-end gap-1">
            <Button size="sm" variant="outline" onClick={() => { setSelected(r); setOp("credit"); }}><Plus className="mr-1 h-3.5 w-3.5" /> Credit</Button>
            <Button size="sm" variant="ghost" onClick={() => { setSelected(r); setOp("debit"); }}><Minus className="mr-1 h-3.5 w-3.5" /> Debit</Button>
          </div>
        )}
      />
      <Dialog open={!!selected} onOpenChange={(o) => !o && setSelected(null)}>
        <DialogContent>
          <DialogHeader><DialogTitle>{op === "credit" ? "Credit" : "Debit"} — {selected?.name}</DialogTitle></DialogHeader>
          <div className="grid gap-3">
            <div className="grid grid-cols-2 gap-3">
              <div className="space-y-1.5"><Label>Amount</Label><Input value={amt} onChange={(e) => setAmt(e.target.value)} type="number" /></div>
              <div className="space-y-1.5"><Label>Currency</Label>
                <Select value={cur} onValueChange={(v) => setCur(v as "GEL" | "WGC")}>
                  <SelectTrigger><SelectValue /></SelectTrigger>
                  <SelectContent><SelectItem value="GEL">GEL (₾)</SelectItem><SelectItem value="WGC">WGC</SelectItem></SelectContent>
                </Select>
              </div>
            </div>
            <div className="space-y-1.5"><Label>Reason</Label><Input value={reason} onChange={(e) => setReason(e.target.value)} placeholder="Audit note" /></div>
          </div>
          <DialogFooter>
            <Button variant="ghost" onClick={() => setSelected(null)}>Cancel</Button>
            <Button className="gradient-primary text-primary-foreground" onClick={() => { toast.success(`${op === "credit" ? "Credited" : "Debited"} ${amt} ${cur} — ${selected?.name}`); setSelected(null); }}>Confirm</Button>
          </DialogFooter>
        </DialogContent>
      </Dialog>
    </div>
  );
}
