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 { Badge } from "@/components/ui/badge";
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from "@/components/ui/select";
import { players } from "@/features/_mock/data";
import { formatGEL, formatWGC } from "@/lib/currency";
import { ArrowDownRight, ArrowUpRight, DollarSign, TrendingUp, TrendingDown } from "lucide-react";

export const Route = createFileRoute("/admin/transactions")({
  head: () => ({ meta: [{ title: "Transactions — Admin" }, { name: "description", content: "Balance and coin movements across the platform." }] }),
  component: AdminTransactionsPage,
});

type Tx = { id: string; user: string; date: string; kind: "topup" | "purchase" | "convert" | "refund" | "reward" | "payout"; currency: "GEL" | "WGC"; amount: number; note: string };
const rows: Tx[] = Array.from({ length: 30 }, (_, i) => ({
  id: `tx-${5000 + i}`,
  user: players[i % players.length].name,
  date: `2026-07-${(24 - (i % 24)).toString().padStart(2, "0")} ${(10 + (i % 12)).toString().padStart(2, "0")}:${((i * 7) % 60).toString().padStart(2, "0")}`,
  kind: (["topup", "purchase", "convert", "purchase", "reward", "refund", "payout"] as const)[i % 7],
  currency: (i % 3 === 0 ? "WGC" : "GEL") as "GEL" | "WGC",
  amount: [10, -4.99, 500, -9.99, 120, 5, -3.49][i % 7],
  note: ["Card top-up", "VIP — 30 days", "5 ₾ → 500 WGC", "Premium — 30 days", "Daily reward", "Refund", "Marketplace sale"][i % 7],
}));

const TONE: Record<Tx["kind"], string> = { topup: "border-success/40 text-success", purchase: "border-destructive/40 text-destructive", convert: "border-secondary/40 text-secondary", refund: "border-warning/40 text-warning", reward: "border-primary/40 text-primary", payout: "border-primary/40 text-primary" };

function AdminTransactionsPage() {
  const [q, setQ] = useState("");
  const [kind, setKind] = useState("all");
  const filtered = useMemo(() => rows.filter((r) => (kind === "all" || r.kind === kind) && (q === "" || r.user.toLowerCase().includes(q.toLowerCase()) || r.id.includes(q))), [q, kind]);

  const gelIn = rows.filter((r) => r.currency === "GEL" && r.amount > 0).reduce((a, b) => a + b.amount, 0);
  const gelOut = rows.filter((r) => r.currency === "GEL" && r.amount < 0).reduce((a, b) => a + Math.abs(b.amount), 0);
  const wgcMov = rows.filter((r) => r.currency === "WGC").reduce((a, b) => a + Math.abs(b.amount), 0);

  const cols: Column<Tx>[] = [
    { key: "d", header: "When", cell: (r) => <span className="text-muted-foreground">{r.date}</span> },
    { key: "u", header: "User", cell: (r) => r.user },
    { key: "n", header: "Description", cell: (r) => r.note },
    { key: "k", header: "Type", cell: (r) => <Badge variant="outline" className={`capitalize ${TONE[r.kind]}`}>{r.kind}</Badge> },
    { key: "a", header: "Amount", className: "text-right", cell: (r) => (
      <div className={`flex items-center justify-end gap-1 font-mono ${r.amount < 0 ? "text-destructive" : "text-success"}`}>
        {r.amount < 0 ? <ArrowUpRight className="h-3.5 w-3.5" /> : <ArrowDownRight className="h-3.5 w-3.5" />}
        {r.currency === "GEL" ? formatGEL(Math.abs(r.amount)) : formatWGC(Math.abs(r.amount))}
      </div>
    )},
  ];

  return (
    <div>
      <PageHeader title="Transactions" description="Money and coin movements across the platform." />
      <div className="mb-4 grid grid-cols-2 gap-3 md:grid-cols-4">
        <StatCard label="Inflow (GEL)" value={formatGEL(gelIn)} tone="success" icon={<TrendingUp className="h-4 w-4" />} />
        <StatCard label="Outflow (GEL)" value={formatGEL(gelOut)} tone="destructive" icon={<TrendingDown className="h-4 w-4" />} />
        <StatCard label="Net (GEL)" value={formatGEL(gelIn - gelOut)} tone="primary" icon={<DollarSign className="h-4 w-4" />} />
        <StatCard label="WGC volume" value={formatWGC(wgcMov)} tone="primary" />
      </div>
      <AdminDataTable
        rows={filtered} columns={cols} search={q} onSearchChange={setQ}
        filters={
          <Select value={kind} onValueChange={setKind}>
            <SelectTrigger className="w-[160px]"><SelectValue /></SelectTrigger>
            <SelectContent><SelectItem value="all">All types</SelectItem><SelectItem value="topup">Top-up</SelectItem><SelectItem value="purchase">Purchase</SelectItem><SelectItem value="convert">Convert</SelectItem><SelectItem value="refund">Refund</SelectItem><SelectItem value="reward">Reward</SelectItem><SelectItem value="payout">Payout</SelectItem></SelectContent>
          </Select>
        }
      />
    </div>
  );
}
