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

export const Route = createFileRoute("/_authenticated/recharge-history")({
  component: RechargeHistory,
});

const STATUS: Record<string, { cls: string; label: string; Icon: any }> = {
  SUCCESS: { cls: "bg-emerald-100 text-emerald-700 dark:bg-emerald-950/40", label: "সফল", Icon: CheckCircle2 },
  FAILED: { cls: "bg-red-100 text-red-700 dark:bg-red-950/40", label: "ব্যর্থ", Icon: XCircle },
  PENDING: { cls: "bg-amber-100 text-amber-700 dark:bg-amber-950/40", label: "অপেক্ষমান", Icon: Clock },
  SUCCESS_UNSETTLED: { cls: "bg-orange-100 text-orange-700", label: "সেটেল হয়নি", Icon: Clock },
};

function RechargeHistory() {
  const list = useServerFn(listMyRecharges);
  const check = useServerFn(checkRechargeStatus);
  const q = useQuery({ queryKey: ["my-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 ?? "আপডেট হয়েছে"}`);
      q.refetch();
    } catch (e: any) {
      toast.error(e?.message ?? "চেক ব্যর্থ");
    } finally {
      setBusy(null);
    }
  };

  return (
    <div className="min-h-screen bg-background max-w-[480px] mx-auto">
      <header className="px-4 pt-4 pb-6 text-primary-foreground rounded-b-3xl" style={{ background: "var(--gradient-primary)" }}>
        <div className="flex items-center gap-3">
          <Link to="/" className="h-10 w-10 rounded-full bg-white/15 backdrop-blur grid place-items-center">
            <ArrowLeft className="h-5 w-5" />
          </Link>
          <div className="flex-1">
            <h1 className="text-lg font-bold leading-tight">রিচার্জ হিস্ট্রি</h1>
            <p className="text-xs opacity-80">আপনার সাম্প্রতিক রিচার্জ</p>
          </div>
          <button onClick={() => q.refetch()} className="h-10 w-10 rounded-full bg-white/15 grid place-items-center">
            <RefreshCw className={`h-4 w-4 ${q.isFetching ? "animate-spin" : ""}`} />
          </button>
        </div>
      </header>

      <main className="px-4 -mt-3 pb-24">
        {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="bg-card rounded-2xl border p-8 text-center text-sm text-muted-foreground">
            <Smartphone className="h-8 w-8 mx-auto text-muted-foreground/50" />
            <p className="mt-2">এখনো কোনো রিচার্জ নেই</p>
            <Link to="/recharge" className="mt-3 inline-block px-4 h-10 leading-10 rounded-full bg-primary text-primary-foreground font-semibold text-sm">
              রিচার্জ করুন
            </Link>
          </div>
        ) : (
          <div className="space-y-2">
            {q.data.map((r: any) => {
              const st = STATUS[r.status] ?? { cls: "bg-muted text-muted-foreground", label: r.status, Icon: Clock };
              const Icon = st.Icon;
              return (
                <div key={r.id} className="bg-card border rounded-2xl p-3 flex gap-3 items-start">
                  <div className="h-10 w-10 rounded-xl bg-primary/10 grid place-items-center text-primary shrink-0">
                    <Smartphone className="h-5 w-5" />
                  </div>
                  <div className="flex-1 min-w-0">
                    <div className="flex items-center gap-2 flex-wrap">
                      <p className="font-bold text-sm">{r.operator}</p>
                      <span className={`inline-flex items-center gap-1 px-2 h-5 rounded-full text-[10px] font-bold ${st.cls}`}>
                        <Icon className="h-3 w-3" /> {st.label}
                      </span>
                    </div>
                    <p className="text-xs text-muted-foreground">{r.number}</p>
                    {r.message && <p className="text-[11px] text-muted-foreground mt-0.5 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>
                    {r.status !== "SUCCESS" && (
                      <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>
        )}
      </main>
    </div>
  );
}
