// src/pages/Invoices.jsx (FINAL - + Wallet balance + Pay with wallet + Apply Coupon + Expire remaining + Refresh Guard)
// ✅ نمایش کیف پول: GET /api/billing/me/wallet/
// ✅ پرداخت با کیف پول: POST /api/billing/invoices/{invoice_id}/pay-with-wallet/
// ✅ اعمال کد تخفیف روی فاکتور: POST /api/billing/invoices/apply-coupon/ { invoice_id, coupon_code }
// ✅ بعد از اعمال موفق: توست + رفرش لیست + رفرش جزئیات فاکتور انتخاب‌شده
// ✅ نمایش مدت‌زمان باقی‌مانده تا اکسپایر: اگر >= 24h => روز، اگر < 24h => ساعت (بدون تایمر)
// ✅ دکمه بروزرسانی ضد اسپم شد (cooldown + inFlight lock + countdown)

import React, { useEffect, useMemo, useRef, useState } from "react";
import { Axiosinstance } from "../services/auth/Axiosinstance";
import { useToast } from "../components/ToastProvider";
import {
  LuChevronLeft,
  LuCreditCard,
  LuRefreshCcw,
  LuTag,
  LuCheck,
  LuWallet,
} from "react-icons/lu";

function formatPrice(v) {
  try {
    return Number(v || 0).toLocaleString("fa-IR");
  } catch {
    return v;
  }
}

function formatDate(iso) {
  if (!iso) return "-";
  try {
    return new Date(iso).toLocaleString("fa-IR");
  } catch {
    return iso;
  }
}

function formatExpireRemaining(expiresAtIso) {
  if (!expiresAtIso) return "-";

  const exp = new Date(expiresAtIso);
  const expMs = exp.getTime();
  if (!Number.isFinite(expMs)) return "-";

  const nowMs = Date.now();
  const diffMs = expMs - nowMs;

  if (diffMs <= 0) return "منقضی شده";

  const diffHours = diffMs / (1000 * 60 * 60);

  if (diffHours < 24) {
    const h = Math.max(1, Math.ceil(diffHours));
    return `${String(h).toLocaleString("fa-IR")} ساعت مانده`;
  }

  const diffDays = diffMs / (1000 * 60 * 60 * 24);
  const d = Math.max(1, Math.ceil(diffDays));
  return `${String(d).toLocaleString("fa-IR")} روز مانده`;
}

function statusMeta(status) {
  const s = (status || "").toLowerCase();
  if (s === "paid")
    return {
      label: "پرداخت‌شده",
      badge: "border-emerald-500/30 bg-emerald-500/10 text-emerald-700 dark:text-emerald-200",
    };
  if (s === "pending")
    return {
      label: "در انتظار پرداخت",
      badge: "border-yellow-500/30 bg-yellow-500/10 text-yellow-700 dark:text-yellow-200",
    };
  if (s === "failed")
    return {
      label: "ناموفق",
      badge: "border-red-500/30 bg-red-500/10 text-red-700 dark:text-red-200",
    };
  if (s === "canceled" || s === "cancelled")
    return {
      label: "لغوشده",
      badge:
        "border-black/10 bg-black/5 text-black/60 dark:border-white/10 dark:bg-white/10 dark:text-white/70",
    };
  if (s === "expired")
    return {
      label: "منقضی شده",
      badge:
        "border-black/10 bg-black/5 text-black/60 dark:border-white/10 dark:bg-white/10 dark:text-white/70",
    };
  return {
    label: status || "-",
    badge:
      "border-black/10 bg-black/5 text-black/60 dark:border-white/10 dark:bg-white/10 dark:text-white/70",
  };
}

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;

  // DRF field errors
  if (Array.isArray(d.invoice_id) && d.invoice_id[0]) return d.invoice_id[0];
  if (Array.isArray(d.coupon_code) && d.coupon_code[0]) return d.coupon_code[0];

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

function Invoices() {
  const { success, error: toastError, info } = useToast();

  const [invoices, setInvoices] = useState([]);
  const [selected, setSelected] = useState(null);

  // ✅ subscription (پلن فعلی)
  const [subscription, setSubscription] = useState(null);
  const [subLoading, setSubLoading] = useState(true);

  // ✅ wallet
  const [wallet, setWallet] = useState(null);
  const [walletLoading, setWalletLoading] = useState(true);

  const [loading, setLoading] = useState(true);
  const [paying, setPaying] = useState(false);
  const [walletPaying, setWalletPaying] = useState(false);

  const [query, setQuery] = useState("");
  const [statusFilter, setStatusFilter] = useState("all");

  // ✅ Coupon UI state
  const [couponCode, setCouponCode] = useState("");
  const [applyingCoupon, setApplyingCoupon] = useState(false);

  /* ==================== ✅ 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 fetchInvoices = async ({ silent = false } = {}) => {
    setLoading(true);
    try {
      const res = await Axiosinstance.get("billing/me/invoices/");
      setInvoices(res.data || []);
      if (!silent) success("فاکتورها بروزرسانی شد.", { title: "پرداخت‌ها" });
      return res.data || [];
    } catch (e) {
      if (!silent) toastError(getErrMsg(e, "خطا در دریافت فاکتورها"), { title: "خطا" });
      return null;
    } finally {
      setLoading(false);
    }
  };

  const fetchSubscription = async ({ silent = true } = {}) => {
    setSubLoading(true);
    try {
      const res = await Axiosinstance.get("billing/me/subscription/");
      setSubscription(res.data || null);
      return res.data || null;
    } catch {
      setSubscription(null);
      return null;
    } finally {
      setSubLoading(false);
      void silent;
    }
  };

  const fetchWallet = async ({ silent = true } = {}) => {
    setWalletLoading(true);
    try {
      const res = await Axiosinstance.get("billing/me/wallet/");
      setWallet(res.data || null);
      return res.data || null;
    } catch (e) {
      // بهتره اینجا توست نزنیم مگر اینکه بخوای
      if (!silent) toastError(getErrMsg(e, "خطا در دریافت کیف پول"), { title: "کیف پول" });
      setWallet(null);
      return null;
    } finally {
      setWalletLoading(false);
      void silent;
    }
  };

  // ✅ after list refresh, keep selected in sync (so discount reflects)
  const syncSelectedFromList = (invoiceId, list) => {
    if (!invoiceId) return null;
    const found = (list || []).find((x) => x?.id === invoiceId) || null;
    return found;
  };

  const refreshAll = async ({ toast = false } = {}) => {
    const selId = selected?.id || null;

    const [list] = await Promise.all([
      fetchInvoices({ silent: !toast }),
      fetchSubscription({ silent: true }),
      fetchWallet({ silent: true }),
    ]);

    if (selId && Array.isArray(list)) {
      const updated = syncSelectedFromList(selId, list);
      if (updated) setSelected(updated);
    }

    if (toast) success("اطلاعات بروزرسانی شد.", { title: "پرداخت‌ها" });
  };

  const guardedRefresh = async () => {
    const now = Date.now();

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

    // 2) cooldown
    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;
    }

    // 3) اجرا
    refreshInFlightRef.current = true;
    refreshLastAtRef.current = now;
    setCooldownLeftMs(REFRESH_COOLDOWN_MS);

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

  // ✅ Callback handler: /api/billing/payments/callback/?invoice_id=...
  const handlePaymentCallback = async () => {
    const url = new URL(window.location.href);
    const invoiceId = url.searchParams.get("invoice_id");

    if (!invoiceId) return;

    info("در حال بررسی پرداخت...", { title: "پرداخت" });
    try {
      const res = await Axiosinstance.get("billing/payments/callback/", {
        params: { invoice_id: invoiceId },
      });

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

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

      // بعد از callback رفرش بدون اسپم
      refreshLastAtRef.current = Date.now();
      setCooldownLeftMs(REFRESH_COOLDOWN_MS);

      await refreshAll({ toast: false });
    } catch (e) {
      toastError(getErrMsg(e, "پرداخت ناموفق بود."), { title: "پرداخت ناموفق" });

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

      refreshLastAtRef.current = Date.now();
      setCooldownLeftMs(REFRESH_COOLDOWN_MS);

      await fetchInvoices({ silent: true });
      await fetchWallet({ silent: true });
    }
  };

  useEffect(() => {
    fetchInvoices({ silent: true });
    fetchSubscription({ silent: true });
    fetchWallet({ silent: true });
    handlePaymentCallback();
    // eslint-disable-next-line react-hooks/exhaustive-deps
  }, []);

  const currentPlanId = subscription?.plan?.id || null;
  const currentPlanName = subscription?.plan?.name || null;
  const subStatus = subscription?.status || null;

  const walletBalance = Number(wallet?.balance || 0);

  const filtered = useMemo(() => {
    const q = query.trim().toLowerCase();
    return (invoices || [])
      .filter((inv) => {
        if (statusFilter === "all") return true;
        return (inv?.status || "").toLowerCase() === statusFilter;
      })
      .filter((inv) => {
        if (!q) return true;
        const hay = [inv?.number, inv?.status, inv?.description, inv?.plan?.name, inv?.plan?.slug]
          .filter(Boolean)
          .join(" ")
          .toLowerCase();
        return hay.includes(q);
      })
      .sort((a, b) => {
        const da = new Date(a?.created_at || 0).getTime();
        const db = new Date(b?.created_at || 0).getTime();
        return db - da;
      });
  }, [invoices, query, statusFilter]);

  const openInvoice = (inv) => {
    setSelected(inv);
    setCouponCode(""); // reset input
  };
  const closeInvoice = () => {
    setSelected(null);
    setCouponCode("");
  };

  const startPayment = async (invoiceId) => {
    if (!invoiceId) return;

    setPaying(true);
    try {
      const res = await Axiosinstance.post("billing/payments/init/", {
        invoice_id: invoiceId,
      });

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

      if (!redirectUrl) {
        toastError("لینک پرداخت از سرور برنگشت. پاسخ init را در console ببین.", { title: "خطا" });
        console.log("payments/init response:", data);
        return;
      }

      info("در حال انتقال به درگاه پرداخت...", { title: "پرداخت" });
      window.location.href = redirectUrl;
    } catch (e) {
      toastError(getErrMsg(e, "خطا در شروع پرداخت"), { title: "خطا" });
    } finally {
      setPaying(false);
    }
  };

  // ✅ Pay with wallet
  const payWithWallet = async () => {
    const invoiceId = selected?.id;
    if (!invoiceId) return toastError("فاکتور انتخاب نشده.", { title: "خطا" });

    const amount = Number(selected?.final_amount || 0);
    if (walletBalance < amount) {
      return toastError("موجودی کیف پول کافی نیست.", { title: "کیف پول" });
    }

    setWalletPaying(true);
    try {
      const res = await Axiosinstance.post(`billing/invoices/${invoiceId}/pay-with-wallet/`);
      const msg = res?.data?.detail || "پرداخت با کیف پول انجام شد ✅";
      success(msg, { title: "کیف پول" });

      // اگر بک‌اند wallet جدید برگردوند، همون رو ست کن
      if (res?.data?.wallet) setWallet(res.data.wallet);

      // رفرش لیست و سینک selected + subscription + wallet
      await refreshAll({ toast: false });

      // ✅ چون تازه رفرش کردیم، کول‌داون رو هم ست کنیم تا با دکمه اسپم نشه
      refreshLastAtRef.current = Date.now();
      setCooldownLeftMs(REFRESH_COOLDOWN_MS);
    } catch (e) {
      toastError(getErrMsg(e, "پرداخت با کیف پول ناموفق بود."), { title: "کیف پول" });
      // بهتره موجودی رو هم دوباره بگیریم
      await fetchWallet({ silent: true });
    } finally {
      setWalletPaying(false);
    }
  };

  // ✅ Apply coupon
  const applyCoupon = async () => {
    const invoiceId = selected?.id;
    const code = couponCode.trim();

    if (!invoiceId) return toastError("فاکتور انتخاب نشده.", { title: "خطا" });
    if (!code) return toastError("کد تخفیف را وارد کنید.", { title: "کد تخفیف" });

    setApplyingCoupon(true);
    try {
      const res = await Axiosinstance.post("billing/invoices/apply-coupon/", {
        invoice_id: invoiceId,
        coupon_code: code,
      });

      const msg = res?.data?.detail || res?.data?.message || "کد تخفیف با موفقیت اعمال شد ✅";
      success(msg, { title: "کد تخفیف" });

      // رفرش لیست و سینک فاکتور انتخاب‌شده
      const invRes = await Axiosinstance.get("billing/me/invoices/");
      const list = invRes.data || [];
      setInvoices(list);

      const updated = syncSelectedFromList(invoiceId, list);
      if (updated) setSelected(updated);

      setCouponCode("");

      // ✅ چون تازه رفرش کردیم، کول‌داون رو هم ست کنیم تا با دکمه اسپم نشه
      refreshLastAtRef.current = Date.now();
      setCooldownLeftMs(REFRESH_COOLDOWN_MS);
    } catch (e) {
      toastError(getErrMsg(e, "اعمال کد تخفیف ناموفق بود."), { title: "کد تخفیف" });
    } finally {
      setApplyingCoupon(false);
    }
  };

  const selectedIsPending = String(selected?.status || "").toLowerCase() === "pending";
  const selectedAmount = Number(selected?.final_amount || 0);
  const walletCanPay = walletBalance >= selectedAmount;

  const refreshDisabled = loading || subLoading || walletLoading || cooldownLeftMs > 0;
  const refreshLabel =
    loading || subLoading || walletLoading
      ? "درحال بروزرسانی..."
      : cooldownLeftMs > 0
      ? `بروزرسانی`
      : "بروزرسانی";

  return (
    <div className="dark:text-white w-full">
      <div className="mb-5 rounded-2xl 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">
              فاکتورهای خرید پلن و جزئیات هر فاکتور
            </p>
          </div>

          <div className="flex items-center gap-2 w-full lg:w-auto">
            {selected && (
              <button
                type="button"
                onClick={closeInvoice}
                className="px-3 py-2 rounded-xl 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 gap-2"
              >
                <LuChevronLeft className="w-4 h-4 rotate-180 text-[#43BEFF] dark:text-white" />
                برگشت به لیست
              </button>
            )}

            <button
              type="button"
              onClick={guardedRefresh}
              disabled={refreshDisabled}
              className="md:w-auto w-fit px-4 py-2 shadow rounded-xl bg-white dark:bg-[#16325b]
                              border border-black/10 dark:border-white/10 hover:bg-black/5 dark:hover:bg-white/10
                              text-sm 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>

      {/* ✅ Current plan + Wallet cards */}
      <div className="mt-5 grid md:grid-cols-2 gap-3">
        {/* Current plan card */}
        <div className="rounded-xl shadow border border-[#43BEFF] dark:border-white/10 bg-white dark:bg-[#16325b] p-4">
          <div className="flex flex-col md:flex-row md:items-center md:justify-between gap-3">
            <div>
              <div className="text-sm font-semibold text-black dark:text-white">پلن فعال فعلی شما</div>

              {subLoading ? (
                <div className="text-sm text-black/60 dark:text-white/70 mt-1">در حال دریافت اطلاعات...</div>
              ) : subscription?.plan ? (
                <div className="mt-1 text-sm text-black/70 dark:text-white/80">
                  <span className="font-bold text-black dark:text-white">{currentPlanName}</span>{" "}
                  <span className="opacity-70">(وضعیت: {subStatus === "active" ? "فعال" : subStatus})</span>
                </div>
              ) : (
                <div className="text-sm text-black/60 dark:text-white/70 mt-1">شما هنوز اشتراک فعالی ندارید.</div>
              )}
            </div>

            {subscription?.plan && (
              <div className="flex flex-wrap gap-2 text-xs">
                <span className="px-3 py-1 rounded-full bg-[#A1E3F980] dark:bg-[#A1E3F919] border border-black/0 dark:border-white/10 text-black/70 dark:text-white/80">
                  شروع: {formatDate(subscription.started_at)}
                </span>
                <span className="px-3 py-1 rounded-full bg-[#A1E3F980] dark:bg-[#A1E3F919] border border-black/0 dark:border-white/10 text-black/70 dark:text-white/80">
                  تمدید خودکار: {subscription.auto_renew ? "روشن" : "خاموش"}
                </span>
              </div>
            )}
          </div>
        </div>

        {/* Wallet card */}
        <div className="rounded-xl shadow border border-black/10 dark:border-white/10 bg-white dark:bg-[#16325b] p-4">
          <div className="flex items-start justify-between gap-3">
            <div>
              <div className="text-sm font-semibold text-black dark:text-white flex items-center gap-2">
                <LuWallet className="w-4 h-4 text-[#43BEFF] dark:text-white" />
                کیف پول
              </div>

              {walletLoading ? (
                <div className="text-sm text-black/60 dark:text-white/70 mt-1">در حال دریافت موجودی...</div>
              ) : wallet ? (
                <div className="mt-2">
                  <div className="text-lg font-extrabold text-black dark:text-white">
                    {formatPrice(wallet.balance)}{" "}
                    <span className="text-xs opacity-70">{selected?.currency || "IRR"}</span>
                  </div>
                  <div className="text-xs text-black/50 dark:text-white/60 mt-1">
                    بروزرسانی: {wallet.updated_at ? formatDate(wallet.updated_at) : "-"}
                  </div>
                </div>
              ) : (
                <div className="text-sm text-black/60 dark:text-white/70 mt-1">اطلاعات کیف پول در دسترس نیست.</div>
              )}
            </div>

            <button
              type="button"
              onClick={() => fetchWallet({ silent: false })}
              className="px-3 py-2 rounded-xl 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 gap-2"
            >
              <LuRefreshCcw className={`w-4 h-4 text-[#43BEFF] dark:text-white ${walletLoading ? "animate-spin" : ""}`} />
              بروزرسانی
            </button>
          </div>
        </div>
      </div>

      {/* Filters (only in list view) */}
      {!selected && (
        <div className="mt-5 flex flex-col md:flex-row gap-3 md:items-center">
          <select
            value={statusFilter}
            onChange={(e) => setStatusFilter(e.target.value)}
            className="md:w-52 w-full rounded-xl shadow bg-[#A1E3F980] dark:bg-[#16325b] border border-black/0 dark:border-white/10 px-3 py-2 text-sm outline-none text-black dark:text-white"
          >
            <option value="all">همه وضعیت‌ها</option>
            <option value="pending">در انتظار پرداخت</option>
            <option value="paid">پرداخت‌شده</option>
            <option value="failed">ناموفق</option>
            <option value="canceled">لغوشده</option>
          </select>
        </div>
      )}

      {/* Loading */}
      {loading && (
        <div className="mt-5 space-y-3">
          {[1, 2, 3].map((i) => (
            <div
              key={i}
              className="h-16 rounded-xl shadow bg-white dark:bg-[#16325b] border border-black/10 dark:border-white/10 animate-pulse"
            />
          ))}
        </div>
      )}

      {/* Empty */}
      {!loading && invoices.length === 0 && (
        <div className="mt-5 p-4 rounded-xl shadow border border-black/10 dark:border-white/10 bg-white dark:bg-[#16325b] text-sm text-black/70 dark:text-white/80">
          هنوز هیچ فاکتوری ندارید.
        </div>
      )}

      {/* LIST VIEW */}
      {!selected && !loading && filtered.length > 0 && (
        <div className="mt-5 space-y-3">
          {filtered.map((inv) => {
            const meta = statusMeta(inv.status);
            const canPay = (inv?.status || "").toLowerCase() === "pending";
            const isCurrentPlanInvoice = currentPlanId && inv?.plan?.id === currentPlanId && subStatus === "active";

            const expText = formatExpireRemaining(inv?.expires_at);
            const showExpire = canPay && inv?.expires_at;

            return (
              <button
                key={inv.id}
                type="button"
                onClick={() => openInvoice(inv)}
                className={`w-full text-right p-4 rounded-xl shadow border bg-white dark:bg-[#16325b] transition sm:flex items-center justify-between gap-3
                  ${
                    isCurrentPlanInvoice
                      ? "border-[#43BEFF]"
                      : "border-black/10 dark:border-white/10 hover:bg-black/5 dark:hover:bg-white/10"
                  }`}
              >
                <div className="sm:flex grid items-center gap-3 min-w-0">
                  <span className={`text-xs px-3 py-1 rounded-full border ${meta.badge}`}>{meta.label}</span>

                  {isCurrentPlanInvoice && (
                    <span className="text-xs px-3 py-1 rounded-full bg-[#43BEFF]/15 border border-[#43BEFF]/30 text-[#0b6ea3] dark:text-[#aee7ff]">
                      پلن فعلی
                    </span>
                  )}

                  <div className="min-w-0">
                    <div className="font-semibold text-sm truncate text-black dark:text-white">
                      {inv.number} — {inv.plan?.name || inv.description || "فاکتور"}
                    </div>

                    <div className="text-xs opacity-70 truncate text-black/60 dark:text-white/70">
                      {formatDate(inv.created_at)}
                      {inv.paid_at ? ` • پرداخت: ${formatDate(inv.paid_at)}` : ""}
                      {showExpire ? ` • انقضا: ${expText}` : ""}
                    </div>
                  </div>
                </div>

                <div className="flex items-center float-end gap-3">
                  <div className="text-left">
                    <div className="text-sm font-bold text-black dark:text-white">
                      {formatPrice(inv.final_amount)}{" "}
                      <span className="text-xs opacity-70">{inv.currency || "IRR"}</span>
                    </div>
                    {canPay && <div className="text-xs text-[#43BEFF] dark:text-white/80">برای پرداخت کلیک کنید</div>}
                  </div>

                  <LuChevronLeft className="w-5 h-5 opacity-60 text-[#43BEFF] dark:text-white" />
                </div>
              </button>
            );
          })}
        </div>
      )}

      {/* DETAIL VIEW */}
      {selected && (
        <div className="mt-5 space-y-4">
          <div className="p-5 rounded-xl shadow border border-[#43BEFF] dark:border-white/10 bg-white dark:bg-[#16325b] space-y-4">
            <div className="flex flex-col md:flex-row md:items-start md:justify-between gap-3">
              <div>
                <h2 className="text-lg font-bold text-black dark:text-white">فاکتور {selected.number}</h2>
                <p className="text-sm opacity-80 text-black/70 dark:text-white/80">{selected.description || "-"}</p>
              </div>

              <span className={`text-xs px-3 py-1 rounded-full border ${statusMeta(selected.status).badge}`}>
                {statusMeta(selected.status).label}
              </span>
            </div>

            <div className="grid md:grid-cols-2 gap-3 text-sm">
              <Info label="پلن" value={selected.plan?.name || "-"} />
              <Info label="وضعیت" value={statusMeta(selected.status).label} />
              <Info label="تاریخ ایجاد" value={formatDate(selected.created_at)} />
              <Info label="تاریخ پرداخت" value={selected.paid_at ? formatDate(selected.paid_at) : "-"} />
              <Info label="واحد پول" value={selected.currency || "IRR"} />
              <Info label="شماره" value={selected.number} />
              <Info label="مهلت پرداخت (باقی‌مانده)" value={formatExpireRemaining(selected.expires_at)} />
              <Info label="تاریخ/ساعت انقضا" value={selected.expires_at ? formatDate(selected.expires_at) : "-"} />
            </div>

            {/* ✅ Wallet hint in detail (only when pending) */}
            {selectedIsPending && (
              <div className="p-3 rounded-xl shadow bg-[#A1E3F980] dark:bg-[#A1E3F919] border border-black/10 dark:border-white/10 flex flex-col md:flex-row md:items-center md:justify-between gap-2">
                <div className="text-sm text-black/70 dark:text-white/80 flex items-center gap-2">
                  <LuWallet className="w-4 h-4" />
                  موجودی کیف پول:
                  <span className="font-extrabold text-black dark:text-white">
                    {walletLoading ? "..." : formatPrice(walletBalance)}
                  </span>
                  <span className="text-xs opacity-70">{selected.currency || "IRR"}</span>
                </div>

                {!walletLoading && wallet && !walletCanPay && (
                  <div className="text-xs text-red-600 dark:text-red-300">
                    موجودی کافی نیست (نیاز: {formatPrice(selectedAmount)} {selected.currency || "IRR"})
                  </div>
                )}
              </div>
            )}

            {/* ✅ Apply Coupon (only when pending) */}
            {selectedIsPending && (
              <div className="pt-3 border-t border-black/10 dark:border-white/10">
                <h3 className="font-semibold mb-3 text-black dark:text-white flex items-center gap-2">
                  <LuTag className="w-4 h-4" />
                  کد تخفیف
                </h3>

                <div className="flex flex-col md:flex-row gap-2 md:items-center">
                  <input
                    value={couponCode}
                    onChange={(e) => setCouponCode(e.target.value)}
                    placeholder="مثلا: YALDA1404"
                    className="w-full md:flex-1 px-3 py-2 rounded-xl shadow bg-white dark:bg-[#001F3F]
                               border border-black/10 dark:border-white/10 outline-none text-sm
                               text-black dark:text-white"
                  />

                  <button
                    type="button"
                    onClick={applyCoupon}
                    disabled={applyingCoupon || !couponCode.trim()}
                    className="px-4 py-2 rounded-xl shadow bg-[#43BEFF] hover:bg-[#34b6ff]
                               text-sm text-white flex items-center justify-center gap-2 disabled:opacity-60"
                  >
                    <LuCheck className="w-4 h-4" />
                    {applyingCoupon ? "در حال اعمال..." : "اعمال تخفیف"}
                  </button>
                </div>

                {selected?.coupon ? (
                  <div className="mt-2 text-xs text-black/60 dark:text-white/70">
                    کد اعمال‌شده:{" "}
                    <span className="font-semibold text-black dark:text-white">{selected.coupon?.code || "—"}</span>
                  </div>
                ) : null}
              </div>
            )}

            <div className="pt-3 border-t border-black/10 dark:border-white/10">
              <h3 className="font-semibold mb-3 text-black dark:text-white">ریز مبالغ</h3>

              <div className="grid md:grid-cols-2 gap-3 text-sm">
                <MoneyRow label="مبلغ پایه" value={selected.base_amount} currency={selected.currency} />
                <MoneyRow label="اعتبار پروریشن" value={selected.proration_credit} currency={selected.currency} />
                <MoneyRow label="تخفیف" value={selected.discount_amount} currency={selected.currency} />
                <MoneyRow label="مالیات" value={selected.tax_amount} currency={selected.currency} />

                <div className="md:col-span-2 p-3 rounded-xl shadow dark:bg-[#A1E3F919] bg-[#A1E3F980] border border-[#A1E3F919] flex items-center justify-between">
                  <span className="text-sm font-semibold text-black dark:text-white">مبلغ نهایی</span>
                  <span className="text-base font-extrabold text-black dark:text-white">
                    {formatPrice(selected.final_amount)}{" "}
                    <span className="text-xs opacity-70">{selected.currency || "IRR"}</span>
                  </span>
                </div>
              </div>
            </div>

            {/* Pay buttons for pending */}
            {selectedIsPending && (
              <div className="pt-3 border-t border-black/10 dark:border-white/10 flex flex-col gap-3">
                <div className="p-3 rounded-xl shadow bg-yellow-500/10 border border-yellow-500/30 text-sm text-black/70 dark:text-white/80">
                  این فاکتور در انتظار پرداخت است.{" "}
                  {selected.expires_at ? (
                    <span className="font-semibold">( {formatExpireRemaining(selected.expires_at)} )</span>
                  ) : null}
                </div>

                <div className="flex flex-col md:flex-row gap-3 md:items-center md:justify-end">
                  {/* Wallet pay */}
                  <button
                    type="button"
                    onClick={payWithWallet}
                    disabled={walletPaying || walletLoading || !wallet || !walletCanPay}
                    className="px-4 py-2 rounded-xl shadow bg-emerald-600 hover:bg-emerald-700
                               text-sm text-white flex items-center justify-center gap-2 disabled:opacity-60"
                    title={!walletCanPay ? "موجودی کافی نیست" : "پرداخت با کیف پول"}
                  >
                    <LuWallet className="w-4 h-4" />
                    {walletPaying ? "در حال پرداخت..." : "پرداخت با کیف پول"}
                  </button>

                  {/* Gateway pay */}
                  <button
                    type="button"
                    onClick={() => startPayment(selected.id)}
                    disabled={paying}
                    className="px-4 py-2 rounded-xl shadow bg-[#43BEFF] hover:bg-[#34b6ff] text-sm text-white flex items-center justify-center gap-2 disabled:opacity-60"
                  >
                    <LuCreditCard className="w-4 h-4" />
                    {paying ? "درحال انتقال به درگاه..." : "ادامه پرداخت"}
                  </button>
                </div>
              </div>
            )}
          </div>
        </div>
      )}
    </div>
  );
}

const Info = ({ label, value }) => (
  <div className="p-3 rounded-xl shadow bg-[#f2f2f2] dark:bg-[#001F3F] border border-black/10 dark:border-white/10">
    <div className="text-xs opacity-70 mb-1 text-black/60 dark:text-white/70">{label}</div>
    <div className="text-sm break-all text-black dark:text-white">{value}</div>
  </div>
);

const MoneyRow = ({ label, value, currency }) => (
  <div className="p-3 rounded-xl shadow bg-[#f2f2f2] dark:bg-[#001F3F] border border-black/10 dark:border-white/10 flex items-center justify-between">
    <span className="text-xs opacity-70 text-black/60 dark:text-white/70">{label}</span>
    <span className="text-sm font-semibold text-black dark:text-white">
      {formatPrice(value)} <span className="text-xs opacity-70">{currency || "IRR"}</span>
    </span>
  </div>
);

export default Invoices;
