// src/pages/Wallet.jsx (FINAL - FIX tx_type credit/debit + Stats/Filters/Row)
// ✅ تشخیص برداشت/واریز از tx_type (و نه علامت amount)
// ✅ stats و فیلترها هم بر اساس type واقعی درست شد

import React, { useEffect, useMemo, useRef, useState } from "react";
import { Axiosinstance } from "../services/auth/Axiosinstance";
import { useNavigate } from "react-router";
import { useToast } from "../components/ToastProvider";
import {
  TbArrowDownRight,
  TbArrowUpRight,
  TbCash,
  TbClock,
  TbSearch,
  TbWallet,
  TbCreditCard,
} from "react-icons/tb";
import { LuRefreshCcw } from "react-icons/lu";

function cn(...a) {
  return a.filter(Boolean).join(" ");
}

function toFa(v) {
  try {
    return String(v).toLocaleString("fa-IR");
  } catch {
    return v;
  }
}

function fmtMoney(v) {
  const n = Number(v ?? 0);
  if (Number.isNaN(n)) return toFa(v);
  return toFa(n);
}

function fmtDate(iso) {
  if (!iso) return "-";
  try {
    const d = new Date(iso);
    return d.toLocaleString("fa-IR", {
      year: "numeric",
      month: "2-digit",
      day: "2-digit",
      hour: "2-digit",
      minute: "2-digit",
    });
  } catch {
    return iso;
  }
}

function pick(obj, keys) {
  for (const k of keys) {
    if (obj && obj[k] !== undefined && obj[k] !== null) return obj[k];
  }
  return undefined;
}

function normalizeType(rawType) {
  const t = String(rawType || "").toLowerCase().trim();
  if (!t) return undefined;

  // انواع رایج
  if (t === "credit" || t === "cr" || t === "deposit") return "credit";
  if (t === "debit" || t === "dr" || t === "withdraw" || t === "withdrawal") return "debit";

  // بعضی بک‌اندها ممکنه اینا رو بده
  if (t.includes("credit")) return "credit";
  if (t.includes("debit")) return "debit";

  return t; // ناشناخته ولی نگه می‌داریم
}

function normalizeTx(tx) {
  const amountRaw = pick(tx, ["amount", "value", "price", "delta", "change"]);
  const createdAt = pick(tx, ["created_at", "createdAt", "date", "timestamp", "time"]);
  const status = pick(tx, ["status", "state"]);
  const description = pick(tx, ["description", "title", "note", "reason"]);
  const ref = pick(tx, ["ref", "reference", "reference_id", "tracking_code", "id"]);

  // ✅ اینجا مهمه: tx_type هم اضافه شد
  const typeRaw = pick(tx, ["tx_type", "type", "kind", "category", "transaction_type"]);
  let type = normalizeType(typeRaw);

  // amount رو عدد می‌کنیم (ولی چون بک‌اند amount رو مثبت میده، علامت‌دهی نمی‌کنیم)
  const amountNum = Number(amountRaw);
  const isNum = !Number.isNaN(amountNum);

  // اگر type نداشت، از روی علامت (یا fallback) حدس بزن
  if (!type && isNum) {
    type = amountNum >= 0 ? "credit" : "debit";
  }

  return {
    id: pick(tx, ["id", "uuid", "pk", "transaction_id"]) ?? ref ?? Math.random(),
    type, // "credit" | "debit" | ...
    amount: isNum ? Math.abs(amountNum) : amountRaw, // ✅ همیشه مثبت برای نمایش
    status,
    createdAt,
    description,
    ref,
    raw: tx,
  };
}

const CARD =
  "rounded-2xl shadow border border-black/10 dark:border-white/10 bg-white/70 dark:bg-white/5 backdrop-blur-sm";
const SOFT =
  "rounded-2xl shadow border border-black/10 dark:border-white/10 bg-[#A1E3F910] dark:bg-[#A1E3F919]";

const INPUT_BASE =
  "w-full dark:bg-[#A1E3F919] bg-[#A1E3F980] rounded-xl shadow grid relative items-center";
const INPUT =
  "h-11 px-4 w-full outline-0 focus:outline-0 rounded-xl bg-transparent text-black dark:text-white placeholder:text-black/50 dark:placeholder:text-white/50";

const getErrMsg = (e, fallback) => {
  const d = e?.response?.data;
  if (!d) return e?.message || fallback;
  if (typeof d === "string") return d;
  if (d.detail) return d.detail;
  if (d.message) return d.message;

  if (Array.isArray(d.amount) && d.amount[0]) return d.amount[0];
  if (Array.isArray(d.invoice_id) && d.invoice_id[0]) return d.invoice_id[0];

  try {
    return JSON.stringify(d);
  } catch {
    return fallback;
  }
};

function Wallet() {
  const navigate = useNavigate();
  const { success, error: toastError, info } = useToast();

  const [wallet, setWallet] = useState(null);
  const [txs, setTxs] = useState([]);
  const [loadingWallet, setLoadingWallet] = useState(true);
  const [loadingTxs, setLoadingTxs] = useState(true);

  // topup
  const [amount, setAmount] = useState("");
  const [topupLoading, setTopupLoading] = useState(false);

  // filters
  const [q, setQ] = useState("");
  const [typeFilter, setTypeFilter] = useState("all");
  const [statusFilter, setStatusFilter] = useState("all");
  const [sort, setSort] = useState("new");

  /* ==================== ✅ Refresh Guard (anti-spam) ==================== */
  const REFRESH_COOLDOWN_MS = 3000;
  const refreshInFlightRef = useRef(false);
  const refreshLastAtRef = useRef(0);
  const refreshToastLockRef = useRef(0);
  const [cooldownLeftMs, setCooldownLeftMs] = useState(0);

  useEffect(() => {
    if (cooldownLeftMs <= 0) return;
    const t = setInterval(() => {
      const left = Math.max(0, REFRESH_COOLDOWN_MS - (Date.now() - refreshLastAtRef.current));
      setCooldownLeftMs(left);
      if (left <= 0) clearInterval(t);
    }, 120);
    return () => clearInterval(t);
  }, [cooldownLeftMs]);
  /* ===================================================================== */

  const fetchWallet = async ({ toast = false } = {}) => {
    setLoadingWallet(true);
    try {
      const res = await Axiosinstance.get("billing/me/wallet/");
      setWallet(res?.data || null);
      if (toast) success("کیف پول بروزرسانی شد.", { title: "کیف پول" });
    } catch (e) {
      toastError(getErrMsg(e, "خطا در دریافت اطلاعات کیف پول"), { title: "خطا" });
    } finally {
      setLoadingWallet(false);
    }
  };

  const fetchTransactions = async ({ toast = false } = {}) => {
    setLoadingTxs(true);
    try {
      const res = await Axiosinstance.get("billing/me/wallet/transactions/");
      const data = res?.data;

      const arr = Array.isArray(data)
        ? data
        : Array.isArray(data?.results)
        ? data.results
        : Array.isArray(data?.data)
        ? data.data
        : [];

      setTxs(arr.map(normalizeTx));
      if (toast) success("تراکنش‌ها بروزرسانی شد.", { title: "تراکنش‌ها" });
    } catch (e) {
      toastError(getErrMsg(e, "خطا در دریافت تراکنش‌های کیف پول"), { title: "خطا" });
    } finally {
      setLoadingTxs(false);
    }
  };

  const refreshAll = async ({ toast = false } = {}) => {
    await Promise.all([fetchWallet({ toast }), fetchTransactions({ toast })]);
  };

  const guardedRefresh = async () => {
    const now = Date.now();
    const loading = loadingWallet || loadingTxs;

    if (refreshInFlightRef.current || loading) {
      if (now - refreshToastLockRef.current > 900) {
        refreshToastLockRef.current = now;
        info("در حال بروزرسانی هستیم...", { title: "بروزرسانی" });
      }
      return;
    }

    const diff = now - refreshLastAtRef.current;
    if (diff < REFRESH_COOLDOWN_MS) {
      const left = REFRESH_COOLDOWN_MS - diff;
      setCooldownLeftMs(left);

      if (now - refreshToastLockRef.current > 900) {
        refreshToastLockRef.current = now;
        info(`لطفاً ${Math.ceil(left / 1000)} ثانیه صبر کن.`, { title: "بروزرسانی" });
      }
      return;
    }

    refreshInFlightRef.current = true;
    refreshLastAtRef.current = now;
    setCooldownLeftMs(REFRESH_COOLDOWN_MS);

    try {
      await refreshAll({ toast: true });
    } finally {
      refreshInFlightRef.current = false;
    }
  };

  useEffect(() => {
    refreshAll();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  // ✅ handle callback if invoice_id exists in URL
  useEffect(() => {
    const url = new URL(window.location.href);
    const invoiceId = url.searchParams.get("invoice_id");
    if (!invoiceId) return;

    const run = async () => {
      info("در حال بررسی پرداخت...", { title: "پرداخت" });

      try {
        const res = await Axiosinstance.get("billing/wallet/callback/", {
          params: { invoice_id: invoiceId },
        });

        const detail = res?.data?.detail || "پرداخت با موفقیت ثبت شد.";
        success(detail, { title: "پرداخت" });

        url.searchParams.delete("invoice_id");
        window.history.replaceState({}, "", url.toString());

        await refreshAll();
        navigate("/receipt");
      } catch (e) {
        const detail = getErrMsg(e, "خطا در تایید پرداخت");
        toastError(detail, { title: "پرداخت ناموفق" });
      }
    };

    run();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, [navigate, info, success, toastError]);

  const balance = useMemo(() => Number(wallet?.balance ?? 0), [wallet]);

  // ✅ Stats: بر اساس type واقعی
  const stats = useMemo(() => {
    let income = 0;
    let outcome = 0;

    for (const t of txs) {
      const amt = Number(t.amount);
      if (Number.isNaN(amt)) continue;

      const tt = String(t.type || "").toLowerCase();
      if (tt === "credit") income += amt;
      else if (tt === "debit") outcome += amt;
      else {
        // fallback قدیمی اگر type نبود
        if (amt >= 0) income += amt;
      }
    }

    const pending = txs.filter((t) => {
      const s = String(t.status || "").toLowerCase();
      return s.includes("pend") || s.includes("wait");
    }).length;

    return { income, outcome, pending, total: txs.length };
  }, [txs]);

  const filtered = useMemo(() => {
    const query = q.trim().toLowerCase();
    let list = [...txs];

    // ✅ type filter: بر اساس type
    if (typeFilter !== "all") {
      list = list.filter((t) => String(t.type || "").toLowerCase() === typeFilter);
    }

    if (statusFilter !== "all") {
      list = list.filter((t) => {
        const s = String(t.status || "").toLowerCase();
        if (statusFilter === "success") return s.includes("succ") || s.includes("paid") || s.includes("done");
        if (statusFilter === "pending") return s.includes("pend") || s.includes("wait");
        if (statusFilter === "failed") return s.includes("fail") || s.includes("error") || s.includes("reject");
        return true;
      });
    }

    if (query) {
      list = list.filter((t) => {
        const blob = [t.description, t.status, t.type, t.ref, t.createdAt, t.amount]
          .filter(Boolean)
          .join(" ")
          .toLowerCase();
        return blob.includes(query);
      });
    }

    list.sort((a, b) => {
      const da = new Date(a.createdAt || 0).getTime();
      const db = new Date(b.createdAt || 0).getTime();
      const aa = Number(a.amount);
      const ab = Number(b.amount);

      if (sort === "new") return db - da;
      if (sort === "old") return da - db;
      if (sort === "amount_desc")
        return (Number.isNaN(ab) ? -Infinity : ab) - (Number.isNaN(aa) ? -Infinity : aa);
      if (sort === "amount_asc")
        return (Number.isNaN(aa) ? Infinity : aa) - (Number.isNaN(ab) ? Infinity : ab);
      return 0;
    });

    return list;
  }, [txs, q, typeFilter, statusFilter, sort]);

  const presets = useMemo(() => [50000, 100000, 200000, 500000, 1000000], []);

  const amountNum = useMemo(() => {
    const cleaned = String(amount || "").replace(/[^\d]/g, "");
    const n = Number(cleaned);
    return Number.isNaN(n) ? 0 : n;
  }, [amount]);

  const amountError = useMemo(() => {
    if (!amountNum) return "مبلغ را وارد کنید.";
    if (amountNum < 1000) return "حداقل مبلغ باید ۱,۰۰۰ ریال باشد.";
    return "";
  }, [amountNum]);

  const initTopup = async () => {
    if (amountError) {
      toastError(amountError, { title: "شارژ کیف پول" });
      return;
    }

    setTopupLoading(true);
    try {
      const res = await Axiosinstance.post("billing/wallet/topup/init/", {
        amount: amountNum,
      });

      const data = res?.data || {};
      const redirect = data.payment_url || data.url || data.redirect_url || data.gateway_url || data.link;

      if (redirect) {
        info("در حال انتقال به صفحه پرداخت...", { title: "پرداخت" });
        window.location.href = redirect;
        return;
      }

      const inv = data.invoice_id || data.id;
      if (inv) {
        success("فاکتور شارژ ساخته شد ✅", { title: "کیف پول" });
        navigate("/receipt");
        return;
      }

      info("درخواست شارژ ثبت شد، اما لینک پرداخت از سمت سرور برنگشت.", { title: "کیف پول" });
      await refreshAll();
    } catch (e) {
      toastError(getErrMsg(e, "خطا در شروع شارژ کیف پول"), { title: "خطا" });
    } finally {
      setTopupLoading(false);
    }
  };

  const loading = loadingWallet || loadingTxs;
  const refreshDisabled = loading || cooldownLeftMs > 0;

  const refreshLabel = loading ? "درحال بروزرسانی..." : "بروزرسانی";

  return (
    <div className="w-full dark:text-white">
      <div className="mb-5 rounded-2xl shadow border border-black/10 dark:border-white/10 bg-[#A1E3F910] shadow dark:bg-[#A1E3F910] p-3 sm:p-4">
        <div className="flex flex-col lg:flex-row gap-3 lg:items-center lg:justify-between min-w-0">
          <div className="min-w-0">
            <h1 className="text-lg sm:text-xl font-extrabold">کیف پول</h1>
            <p className="text-xs sm:text-sm text-black/60 dark:text-white/70 truncate">
              آخرین بروزرسانی:{" "}
              <b className="font-semibold">{wallet?.updated_at ? fmtDate(wallet.updated_at) : "-"}</b>
            </p>
          </div>

          <div className="flex items-center gap-2 w-full lg:w-auto">
            <button
              type="button"
              onClick={guardedRefresh}
              disabled={refreshDisabled}
              className="flex-1 sm:flex-none px-4 py-2 rounded-xl shadow shadow bg-white dark:bg-[#16325b]
                        border border-black/10 dark:border-white/10 hover:bg-black/5 dark:hover:bg-white/10
                        text-sm inline-flex items-center justify-center gap-2 transition disabled:opacity-60"
              title={cooldownLeftMs > 0 ? `تا ${Math.ceil(cooldownLeftMs / 1000)} ثانیه دیگر` : "بروزرسانی کیف پول و تراکنش‌ها"}
            >
              <LuRefreshCcw className={`w-4 h-4 text-[#43BEFF] dark:text-white ${loading ? "animate-spin" : ""}`} />
              {refreshLabel}
            </button>
          </div>
        </div>
      </div>

      {/* Header */}
      <div className={cn(CARD, "p-4 md:p-5 mb-6")}>
        {/* Balance + Topup */}
        <div className="grid lg:grid-cols-3 gap-4">
          {/* Balance */}
          <div className={cn(SOFT, "p-4 md:p-5 lg:col-span-1")}>
            <div className="flex items-center justify-between">
              <div className="text-xs text-black/60 dark:text-white/70">موجودی فعلی</div>
              <TbCash className="w-5 h-5 opacity-70" />
            </div>

            <div className="mt-2 text-2xl font-extrabold text-black dark:text-white">
              {fmtMoney(balance)}
              <span className="text-sm font-semibold opacity-70 mr-2">ریال</span>
            </div>

            <div className="mt-3 text-xs text-black/60 dark:text-white/70">
              شناسه کیف پول: <span className="font-mono">{wallet?.id || "-"}</span>
            </div>
          </div>

          {/* Topup */}
          <div className={cn(SOFT, "p-4 md:p-5 lg:col-span-2")}>
            <div className="flex items-center justify-between gap-3 flex-wrap">
              <div className="flex items-center gap-2">
                <TbCreditCard className="w-5 h-5 opacity-80" />
                <div className="text-sm font-extrabold text-black dark:text-white">شارژ کیف پول</div>
              </div>

              <button
                type="button"
                onClick={initTopup}
                disabled={topupLoading}
                className="px-4 py-2 rounded-xl shadow font-bold text-sm bg-[#A1E3F980] dark:bg-[#A1E3F919] border border-black/10 dark:border-white/10 hover:bg-[#43BEFF40] dark:hover:bg-[#43BEFF40] transition disabled:opacity-60"
              >
                {topupLoading ? "در حال ساخت پرداخت..." : "پرداخت و شارژ"}
              </button>
            </div>

            <div className="mt-4 grid sm:grid-cols-2 gap-3">
              <div className={cn(INPUT_BASE, "pr-3")}>
                <input
                  className={INPUT}
                  placeholder="مبلغ (ریال)"
                  value={amount}
                  onChange={(e) => {
                    const cleaned = e.target.value.replace(/[^\d]/g, "");
                    setAmount(cleaned ? Number(cleaned).toString() : "");
                  }}
                  inputMode="numeric"
                />
              </div>

              <div className="flex flex-wrap gap-2 justify-end sm:justify-start">
                {presets.map((p) => (
                  <button
                    key={p}
                    type="button"
                    onClick={() => setAmount(String(p))}
                    className="px-3 py-2 rounded-xl shadow text-xs font-bold border border-black/10 dark:border-white/10 bg-white/70 dark:bg-white/10 hover:bg-[#43BEFF40] dark:hover:bg-[#43BEFF40] transition"
                  >
                    {fmtMoney(p)}
                  </button>
                ))}
              </div>
            </div>

            <div className="mt-3 text-xs text-black/60 dark:text-white/70 leading-6">
              {amountNum ? (
                <>
                  مبلغ انتخاب‌شده: <b className="text-black dark:text-white">{fmtMoney(amountNum)}</b> ریال
                </>
              ) : (
                "یک مبلغ وارد کن و روی «پرداخت و شارژ» بزن."
              )}
            </div>
          </div>
        </div>

        {/* Stats */}
        <div className="mt-4 grid sm:grid-cols-4 gap-3">
          <Stat title="واریزی‌ها" value={`${fmtMoney(stats.income)}`} icon={<TbArrowDownRight className="w-5 h-5" />} />
          <Stat title="برداشت‌ها" value={`${fmtMoney(stats.outcome)}`} icon={<TbArrowUpRight className="w-5 h-5" />} />
          <Stat title="در انتظار" value={toFa(stats.pending)} icon={<TbClock className="w-5 h-5" />} />
          <Stat title="کل تراکنش‌ها" value={toFa(stats.total)} icon={<TbWallet className="w-5 h-5" />} />
        </div>
      </div>

      {/* Filters + Table */}
      <div className={cn(CARD, "p-4 md:p-5")}>
        <div className="flex items-center justify-between gap-3 flex-wrap">
          <div className="text-sm font-bold text-black dark:text-white">تراکنش‌ها</div>

          <div className="flex items-center gap-3 flex-wrap w-full sm:w-auto">
            {/* search */}
            <div className={cn(INPUT_BASE, "sm:w-[260px] w-full")}>
              <div className="absolute right-3 top-1/2 -translate-y-1/2 opacity-70">
                <TbSearch className="w-5 h-5" />
              </div>
              <input
                className={cn(INPUT, "pr-11")}
                placeholder="جستجو (شرح، وضعیت، مبلغ...)"
                value={q}
                onChange={(e) => setQ(e.target.value)}
              />
            </div>

            {/* type */}
            <select
              value={typeFilter}
              onChange={(e) => setTypeFilter(e.target.value)}
              className="h-11 px-3 rounded-xl shadow bg-[#A1E3F980] dark:bg-[#A1E3F919] border border-black/10 dark:border-white/10 text-sm outline-0"
            >
              <option value="all">همه</option>
              <option value="credit">واریز</option>
              <option value="debit">برداشت</option>
            </select>

            {/* status */}
            <select
              value={statusFilter}
              onChange={(e) => setStatusFilter(e.target.value)}
              className="h-11 px-3 rounded-xl shadow bg-[#A1E3F980] dark:bg-[#A1E3F919] border border-black/10 dark:border-white/10 text-sm outline-0"
            >
              <option value="all">همه وضعیت‌ها</option>
              <option value="success">موفق</option>
              <option value="pending">در انتظار</option>
              <option value="failed">ناموفق</option>
            </select>

            {/* sort */}
            <select
              value={sort}
              onChange={(e) => setSort(e.target.value)}
              className="h-11 px-3 rounded-xl shadow bg-[#A1E3F980] dark:bg-[#A1E3F919] border border-black/10 dark:border-white/10 text-sm outline-0"
            >
              <option value="new">جدیدترین</option>
              <option value="old">قدیمی‌ترین</option>
              <option value="amount_desc">بیشترین مبلغ</option>
              <option value="amount_asc">کمترین مبلغ</option>
            </select>
          </div>
        </div>

        {/* Table */}
        <div className="mt-5 overflow-x-auto">
          <table className="w-full text-sm">
            <thead>
              <tr className="text-black/60 dark:text-white/70">
                <th className="text-right font-semibold py-3 px-3">نوع</th>
                <th className="text-right font-semibold py-3 px-3">مبلغ</th>
                <th className="text-right font-semibold py-3 px-3">وضعیت</th>
                <th className="text-right font-semibold py-3 px-3">تاریخ</th>
                <th className="text-right font-semibold py-3 px-3">شرح</th>
              </tr>
            </thead>

            <tbody>
              {loadingTxs ? (
                [...Array(6)].map((_, i) => (
                  <tr key={i} className="border-t border-black/5 dark:border-white/10">
                    <td className="py-3 px-3"><div className="h-5 w-24 rounded bg-black/5 dark:bg-white/10 animate-pulse" /></td>
                    <td className="py-3 px-3"><div className="h-5 w-28 rounded bg-black/5 dark:bg-white/10 animate-pulse" /></td>
                    <td className="py-3 px-3"><div className="h-5 w-20 rounded bg-black/5 dark:bg-white/10 animate-pulse" /></td>
                    <td className="py-3 px-3"><div className="h-5 w-36 rounded bg-black/5 dark:bg-white/10 animate-pulse" /></td>
                    <td className="py-3 px-3"><div className="h-5 w-56 rounded bg-black/5 dark:bg-white/10 animate-pulse" /></td>
                  </tr>
                ))
              ) : filtered.length === 0 ? (
                <tr className="border-t border-black/5 dark:border-white/10">
                  <td colSpan={5} className="py-10 text-center text-black/50 dark:text-white/60">
                    تراکنشی برای نمایش وجود ندارد.
                  </td>
                </tr>
              ) : (
                filtered.map((t) => <TxRow key={String(t.id)} t={t} />)
              )}
            </tbody>
          </table>
        </div>
      </div>
    </div>
  );
}

function Stat({ title, value, icon }) {
  return (
    <div className="rounded-2xl shadow border border-black/10 dark:border-white/10 bg-white/70 dark:bg-white/10 p-4">
      <div className="flex items-center justify-between text-xs text-black/60 dark:text-white/70">
        <span>{title}</span>
        <span className="opacity-80">{icon}</span>
      </div>
      <div className="mt-2 text-lg font-extrabold text-black dark:text-white">{value}</div>
    </div>
  );
}

function badgeBase() {
  return "inline-flex items-center gap-2 px-3 py-1 rounded-full text-xs border";
}

function TxRow({ t }) {
  const type = String(t.type || "").toLowerCase();

  // ✅ اولویت با type واقعی؛ fallback اگر نبود
  const amountNum = Number(t.amount);
  const isNum = !Number.isNaN(amountNum);

  const isCredit = type === "credit" ? true : type === "debit" ? false : isNum ? amountNum > 0 : false;
  const isDebit = type === "debit" ? true : type === "credit" ? false : isNum ? amountNum < 0 : false;

  const status = String(t.status || "").toLowerCase();
  const isPending = status.includes("pend") || status.includes("wait");
  const isFailed = status.includes("fail") || status.includes("error") || status.includes("reject");
  const isSuccess = !isPending && !isFailed && !!status;

  const typeLabel = isCredit ? "واریز" : isDebit ? "برداشت" : t.type ? String(t.type) : "-";

  const typeBadge = isCredit
    ? "bg-emerald-500/10 border-emerald-500/25 text-emerald-700 dark:text-emerald-200"
    : isDebit
    ? "bg-red-500/10 border-red-500/25 text-red-700 dark:text-red-200"
    : "bg-black/5 border-black/10 text-black/70 dark:text-white/70 dark:bg-white/10 dark:border-white/10";

  const statusBadge = isPending
    ? "bg-amber-500/10 border-amber-500/25 text-amber-700 dark:text-amber-200"
    : isFailed
    ? "bg-red-500/10 border-red-500/25 text-red-700 dark:text-red-200"
    : isSuccess
    ? "bg-emerald-500/10 border-emerald-500/25 text-emerald-700 dark:text-emerald-200"
    : "bg-black/5 border-black/10 text-black/70 dark:text-white/70 dark:bg-white/10 dark:border-white/10";

  return (
    <tr className="border-t border-black/5 dark:border-white/10 hover:bg-black/5 dark:hover:bg-white/5 transition">
      <td className="py-3 px-3">
        <span className={cn(badgeBase(), typeBadge)}>
          {isCredit ? (
            <TbArrowDownRight className="w-4 h-4" />
          ) : isDebit ? (
            <TbArrowUpRight className="w-4 h-4" />
          ) : (
            <TbWallet className="w-4 h-4" />
          )}
          {typeLabel}
        </span>
      </td>

      <td className="py-3 px-3 font-bold">
        <span
          className={cn(
            isCredit
              ? "text-emerald-700 dark:text-emerald-200"
              : isDebit
              ? "text-red-700 dark:text-red-200"
              : "text-black dark:text-white"
          )}
        >
          {isNum ? fmtMoney(Math.abs(amountNum)) : fmtMoney(t.amount)}
        </span>
        <span className="text-xs opacity-70 mr-2">ریال</span>
      </td>

      <td className="py-3 px-3">
        <span className={cn(badgeBase(), statusBadge)}>
          {isPending ? "در انتظار" : isFailed ? "ناموفق" : isSuccess ? "موفق" : t.status ? String(t.status) : "-"}
        </span>
      </td>

      <td className="py-3 px-3 text-black/70 dark:text-white/70">{fmtDate(t.createdAt)}</td>

      <td className="py-3 px-3">
        <div className="text-black dark:text-white font-medium truncate max-w-[420px]">{t.description || "—"}</div>
        {t.ref && (
          <div className="text-[11px] text-black/50 dark:text-white/60 mt-1">
            Ref: <span className="font-mono">{String(t.ref)}</span>
          </div>
        )}
      </td>
    </tr>
  );
}

export default Wallet;
