import { createFileRoute } from "@tanstack/react-router";
import { useServerFn } from "@tanstack/react-start";
import { useQuery } from "@tanstack/react-query";
import { adminListRecharges, checkRechargeStatus } from "@/lib/recharge.functions";
import { Loader2, RefreshCw, Signal, CheckCircle2, XCircle, Clock } from "lucide-react";
import { toast } from "sonner";
import { useState } from "react";

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

const STATUS_STYLE: Record<string, string> = {
  SUCCESS: "bg-emerald-100 text-emerald-700 dark:bg-emerald-950/40",
  FAILED: "bg-red-100 text-red-700 dark:bg-red-950/40",
  PENDING: "bg-amber-100 text-amber-700 dark:bg-amber-950/40",
  SUCCESS_UNSETTLED: "bg-orange-100 text-orange-700 dark:bg-orange-950/40",
};

function StatusPill({ s }: { s: string }) {
  const cls = STATUS_STYLE[s] ?? "bg-muted text-muted-foreground";
  const Icon = s === "SUCCESS" ? CheckCircle2 : s === "FAILED" ? XCircle : Clock;
  return (
    <span className={`inline-flex items-center gap-1 px-2 h-6 rounded-full text-[10px] font-bold ${cls}`}>
      <Icon className="h-3 w-3" /> {s}
    </span>
  );
}

function AdminRechargesPage() {
  const list = useServerFn(adminListRecharges);
  const check = useServerFn(checkRechargeStatus);
  const q = useQuery({ queryKey: ["admin-recharges"], queryFn: () => list() });
  const [busy, setBusy] = useState<string | null>(null);

  const runCheck = async (refid: string) => {
    setBusy(refid);
    try {
      const r = await check({ data: { refid } });
      toast.success(`স্ট্যাটাস: ${r?.RECHARGE_STATUS ?? "UPDATED"}`);
      q.refetch();
    } catch (e: any) {
      toast.error(e?.message ?? "চেক ব্যর্থ");
    } finally {
      setBusy(null);
    }
  };

  return (
    <div className="space-y-4 max-w-3xl mx-auto">
      <div className="flex items-center justify-between">
        <div className="flex items-center gap-2">
          <div className="h-9 w-9 rounded-lg grid place-items-center text-primary-foreground" style={{ background: "var(--gradient-primary)" }}>
            <Signal className="h-5 w-5" />
          </div>
          <div>
            <h1 className="text-lg font-bold">রিচার্জ লগ</h1>
            <p className="text-xs text-muted-foreground">সর্বশেষ ২০০টি রিচার্জ</p>
          </div>
        </div>
        <button onClick={() => q.refetch()} className="h-9 w-9 rounded-lg border grid place-items-center hover:bg-muted">
          <RefreshCw className={`h-4 w-4 ${q.isFetching ? "animate-spin" : ""}`} />
        </button>
      </div>

      {q.isLoading ? (
        <div className="py-20 grid place-items-center"><Loader2 className="h-6 w-6 animate-spin text-primary" /></div>
      ) : !q.data?.length ? (
        <div className="py-16 text-center text-sm text-muted-foreground bg-card rounded-2xl border">কোনো রিচার্জ নেই</div>
      ) : (
        <div className="space-y-2">
          {q.data.map((r: any) => (
            <div key={r.id} className="bg-card border rounded-2xl p-3 flex gap-3 items-start">
              <div className="flex-1 min-w-0">
                <div className="flex items-center gap-2 flex-wrap">
                  <p className="font-bold text-sm">{r.operator} • {r.number}</p>
                  <StatusPill s={r.status} />
                </div>
                <p className="text-[11px] text-muted-foreground mt-0.5 truncate">
                  {r.profiles?.full_name ?? "-"} ({r.profiles?.phone ?? "-"}) • ref: {r.refid}
                </p>
                {r.message && <p className="text-[11px] text-muted-foreground mt-1 line-clamp-2">{r.message}</p>}
                <p className="text-[10px] text-muted-foreground mt-1">{new Date(r.created_at).toLocaleString()}</p>
              </div>
              <div className="text-right shrink-0">
                <p className="font-bold text-primary">৳{Number(r.amount).toLocaleString()}</p>
                <button
                  onClick={() => runCheck(r.refid)}
                  disabled={busy === r.refid}
                  className="mt-1 h-7 px-2 rounded-full border text-[10px] font-semibold hover:bg-muted disabled:opacity-50 flex items-center gap-1"
                >
                  {busy === r.refid ? <Loader2 className="h-3 w-3 animate-spin" /> : <RefreshCw className="h-3 w-3" />}
                  চেক
                </button>
              </div>
            </div>
          ))}
        </div>
      )}
    </div>
  );
}
