import { createFileRoute, Link } from "@tanstack/react-router";
import { useQuery } from "@tanstack/react-query";
import { useServerFn } from "@tanstack/react-start";
import { listMyTransactions, getMyProfile } from "@/lib/bkash.functions";
import { ActionScreen } from "@/components/bkash/ActionScreen";
import { useState } from "react";
import { Send, ArrowDownToLine, Smartphone, Zap, CreditCard, ArrowDownLeft, Plus } from "lucide-react";

export const Route = createFileRoute("/_authenticated/statement")({
  component: StatementPage,
});

const TYPE_META: Record<string, { label: string; icon: any; sign: 1 | -1 }> = {
  send_money: { label: "Send Money", icon: Send, sign: -1 },
  received: { label: "Received", icon: ArrowDownLeft, sign: 1 },
  cash_out: { label: "Cash Out", icon: ArrowDownToLine, sign: -1 },
  mobile_recharge: { label: "Mobile Recharge", icon: Smartphone, sign: -1 },
  pay_bill: { label: "Pay Bill", icon: Zap, sign: -1 },
  payment: { label: "Payment", icon: CreditCard, sign: -1 },
  add_money: { label: "Add Money", icon: Plus, sign: 1 },
};

const FILTERS = [
  { key: "all", label: "সব" },
  { key: "send_money", label: "Send" },
  { key: "received", label: "Received" },
  { key: "cash_out", label: "Cash Out" },
  { key: "pay_bill", label: "Bills" },
  { key: "mobile_recharge", label: "Recharge" },
] as const;

function StatementPage() {
  const list = useServerFn(listMyTransactions);
  const profile = useServerFn(getMyProfile);
  const profileQ = useQuery({ queryKey: ["profile"], queryFn: () => profile() });
  const txQ = useQuery({ queryKey: ["transactions"], queryFn: () => list() });
  const [filter, setFilter] = useState<string>("all");

  const items = (txQ.data ?? []).filter((t: any) => filter === "all" || t.type === filter);

  return (
    <ActionScreen title="স্টেটমেন্ট" subtitle="আপনার সব লেনদেনের ইতিহাস">
      <div className="bg-card rounded-2xl shadow-[var(--shadow-elevated)] p-4 mb-4">
        <p className="text-xs text-muted-foreground">বর্তমান ব্যালেন্স</p>
        <p className="text-2xl font-extrabold tabular-nums mt-0.5">
          ৳ {Number(profileQ.data?.balance ?? 0).toLocaleString("en-BD", { minimumFractionDigits: 2 })}
        </p>
      </div>

      <div className="flex gap-2 overflow-x-auto pb-2 -mx-1 px-1 mb-3 no-scrollbar">
        {FILTERS.map((f) => (
          <button key={f.key} onClick={() => setFilter(f.key)}
            className={`shrink-0 px-3 h-8 rounded-full text-xs font-semibold transition ${
              filter === f.key ? "bg-primary text-primary-foreground" : "bg-muted text-foreground/70"
            }`}>{f.label}</button>
        ))}
      </div>

      <div className="bg-card rounded-2xl shadow-[var(--shadow-card)] divide-y divide-border">
        {txQ.isLoading && <div className="p-8 text-center text-sm text-muted-foreground">লোড হচ্ছে...</div>}
        {!txQ.isLoading && items.length === 0 && (
          <div className="p-8 text-center text-sm text-muted-foreground">
            কোনো লেনদেন নেই। <Link to="/" className="text-primary font-semibold">হোমে ফিরুন</Link>
          </div>
        )}
        {items.map((t: any) => {
          const meta = TYPE_META[t.type] ?? TYPE_META.payment;
          const Icon = meta.icon;
          const positive = meta.sign === 1;
          return (
            <div key={t.id} className="flex items-center gap-3 p-3.5">
              <div className={`h-11 w-11 rounded-full flex items-center justify-center shrink-0 ${positive ? "bg-success/10" : "bg-accent"}`}>
                <Icon className={`h-5 w-5 ${positive ? "text-success" : "text-primary"}`} strokeWidth={2.2} />
              </div>
              <div className="flex-1 min-w-0">
                <p className="font-semibold text-sm truncate">{t.counterparty_name ?? meta.label}</p>
                <p className="text-xs text-muted-foreground truncate">
                  {meta.label} · {new Date(t.created_at).toLocaleString("en-GB", { day: "2-digit", month: "short", year: "numeric", hour: "2-digit", minute: "2-digit" })}
                </p>
                {t.fee > 0 && <p className="text-[10px] text-muted-foreground">ফি ৳{Number(t.fee).toLocaleString()}</p>}
              </div>
              <div className="text-right">
                <p className={`font-bold text-sm tabular-nums ${positive ? "text-success" : "text-foreground"}`}>
                  {positive ? "+" : "-"}৳{Number(t.amount).toLocaleString()}
                </p>
                <p className="text-[10px] text-muted-foreground tabular-nums">ব্যাল ৳{Number(t.balance_after).toLocaleString()}</p>
              </div>
            </div>
          );
        })}
      </div>
      <div className="h-8" />
    </ActionScreen>
  );
}
