import { createFileRoute } from "@tanstack/react-router";
import { queryOptions, useSuspenseQuery, useQueryClient } from "@tanstack/react-query";
import { useState } from "react";
import { useServerFn } from "@tanstack/react-start";
import { listPayments, reviewPayment } from "@/lib/admin.functions";
import { toast } from "sonner";
import { Check, X, Filter } from "lucide-react";

const q = queryOptions({ queryKey: ["admin-payments"], queryFn: () => listPayments() });

export const Route = createFileRoute("/_authenticated/admin/payments")({
  loader: ({ context }) => context.queryClient.ensureQueryData(q),
  component: AdminPayments,
});

function AdminPayments() {
  const { data } = useSuspenseQuery(q);
  const qc = useQueryClient();
  const reviewFn = useServerFn(reviewPayment);
  const [filter, setFilter] = useState<"all" | "pending" | "approved" | "rejected">("pending");

  const filtered = data.payments.filter((p: any) => filter === "all" || p.status === filter);

  const review = async (id: string, action: "approve" | "reject") => {
    const note = action === "reject" ? prompt("Reason (optional):") ?? undefined : undefined;
    try {
      await reviewFn({ data: { paymentId: id, action, note } });
      toast.success(`Payment ${action}d`);
      await qc.invalidateQueries({ queryKey: ["admin-payments"] });
      await qc.invalidateQueries({ queryKey: ["admin-overview"] });
    } catch (e: any) { toast.error(e.message); }
  };

  return (
    <div>
      <div className="mb-6 flex flex-wrap items-center justify-between gap-3">
        <h1 className="font-display text-3xl font-bold">Payments</h1>
        <div className="inline-flex items-center gap-1 rounded-lg border border-border bg-card p-1">
          <Filter className="ml-2 h-4 w-4 text-muted-foreground" />
          {(["pending", "approved", "rejected", "all"] as const).map((s) => (
            <button key={s} onClick={() => setFilter(s)}
              className={`rounded-md px-3 py-1.5 text-xs font-semibold capitalize ${filter === s ? "bg-primary text-primary-foreground" : "text-muted-foreground hover:text-foreground"}`}>
              {s}
            </button>
          ))}
        </div>
      </div>

      <div className="overflow-x-auto rounded-2xl border border-border bg-card">
        <table className="w-full text-sm">
          <thead className="bg-muted/40 text-xs uppercase tracking-wider text-muted-foreground">
            <tr>
              <th className="px-4 py-3 text-left">Date</th>
              <th className="px-4 py-3 text-left">Name / Email</th>
              <th className="px-4 py-3 text-left">Sender # / TrxID</th>
              <th className="px-4 py-3 text-right">Amount</th>
              <th className="px-4 py-3 text-left">Status</th>
              <th className="px-4 py-3 text-right">Actions</th>
            </tr>
          </thead>
          <tbody className="divide-y divide-border">
            {filtered.map((p: any) => (
              <tr key={p.id}>
                <td className="px-4 py-3 text-muted-foreground">{new Date(p.created_at).toLocaleString()}</td>
                <td className="px-4 py-3">
                  <div className="font-medium">{p.full_name}</div>
                  <div className="text-xs text-muted-foreground">{p.email}</div>
                  <div className="text-xs text-muted-foreground">{p.phone}</div>
                </td>
                <td className="px-4 py-3">
                  <div className="font-mono text-xs">{p.sender_number}</div>
                  <div className="font-mono text-xs font-semibold">{p.transaction_id}</div>
                </td>
                <td className="px-4 py-3 text-right font-semibold">৳{Number(p.amount).toLocaleString("en-BD")}</td>
                <td className="px-4 py-3"><StatusPill s={p.status} /></td>
                <td className="px-4 py-3 text-right">
                  {p.status === "pending" ? (
                    <div className="inline-flex gap-2">
                      <button onClick={() => review(p.id, "approve")} className="inline-flex items-center gap-1 rounded-md bg-success px-3 py-1.5 text-xs font-semibold text-success-foreground"><Check className="h-3 w-3" /> Approve</button>
                      <button onClick={() => review(p.id, "reject")} className="inline-flex items-center gap-1 rounded-md bg-destructive px-3 py-1.5 text-xs font-semibold text-destructive-foreground"><X className="h-3 w-3" /> Reject</button>
                    </div>
                  ) : <span className="text-xs text-muted-foreground">{p.admin_note ?? "—"}</span>}
                </td>
              </tr>
            ))}
            {filtered.length === 0 && <tr><td colSpan={6} className="px-4 py-10 text-center text-sm text-muted-foreground">No {filter} payments.</td></tr>}
          </tbody>
        </table>
      </div>
    </div>
  );
}

function StatusPill({ s }: { s: string }) {
  const map: Record<string, string> = {
    pending: "bg-warning/15 text-warning",
    approved: "bg-success/15 text-success",
    rejected: "bg-destructive/15 text-destructive",
  };
  return <span className={`rounded-full px-2 py-0.5 text-xs font-semibold ${map[s]}`}>{s}</span>;
}
