"use client";

import { useEffect, useState, useCallback } from "react";
import Image from "next/image";
import {
  Coins,
  Wallet,
  Zap,
  ShieldCheck,
  Star,
  Receipt,
  CheckCircle2,
  XCircle,
  Clock,
  Gift,
  ArrowDownToLine,
  X,
  ChevronDown,
  Loader2,
} from "lucide-react";
import {
  walletService,
  type CoinPackage,
  type WalletBalance,
  type CoinPurchaseTransaction,
  type WithdrawalTransaction,
  type GiftTransaction,
  type PaginatedResult,
} from "@/services/walletService";
import { useGeneralSettings } from "@/lib/GeneralSettingsContext";
import {
  PaymentModal,
  type PaymentContext,
} from "@/components/payment/PaymentModal";
import { useTranslation } from "@/i18n";

/* ── helpers ────────────────────────────────────────────────────────────────── */

function formatCoins(n: number) {
  if (n >= 1_000_000) return `${(n / 1_000_000).toFixed(1)}M`;
  if (n >= 1_000) return `${(n / 1_000).toFixed(n >= 10_000 ? 0 : 1)}K`;
  return String(n);
}

function coinsPerDollar(pkg: CoinPackage) {
  return Math.round(pkg.coin / pkg.price);
}

function bestValueId(packages: CoinPackage[]): number {
  if (packages.length === 0) return -1;
  return packages.reduce((best, p) =>
    coinsPerDollar(p) > coinsPerDollar(best) ? p : best,
  ).id;
}

type TxTab = "purchases" | "withdrawals" | "gifts";

/* ── Status badge ───────────────────────────────────────────────────────────── */

function StatusBadge({ status }: { status: number }) {
  const { t } = useTranslation();
  const cfg =
    status === 1
      ? {
          label: t("wallet_statusApproved"),
          color: "#10b981",
          bg: "rgba(16,185,129,0.1)",
          icon: CheckCircle2,
        }
      : status === 2
        ? {
            label: t("wallet_statusRejected"),
            color: "#ef4444",
            bg: "rgba(239,68,68,0.1)",
            icon: XCircle,
          }
        : {
            label: t("wallet_statusPending"),
            color: "#f59e0b",
            bg: "rgba(245,158,11,0.1)",
            icon: Clock,
          };
  const Icon = cfg.icon;
  return (
    <span
      className="inline-flex items-center gap-1 px-2 py-0.5 rounded-full text-[10px] font-semibold"
      style={{ background: cfg.bg, color: cfg.color }}
    >
      <Icon size={9} strokeWidth={2.2} />
      {cfg.label}
    </span>
  );
}

/* ── Balance hero ───────────────────────────────────────────────────────────── */

function BalanceHero({
  balance,
  loading,
  sym,
  onWithdraw,
}: {
  balance: WalletBalance | null;
  loading: boolean;
  sym: string;
  onWithdraw: () => void;
}) {
  const { t } = useTranslation();

  return (
    <div
      className="relative overflow-hidden rounded-2xl p-6"
      style={{
        background:
          "linear-gradient(135deg, #1a1208 0%, #0f1a0a 40%, #12100a 100%)",
        border: "1px solid rgba(245,158,11,0.18)",
        boxShadow:
          "0 0 60px rgba(245,158,11,0.08), 0 20px 60px rgba(0,0,0,0.5)",
        animation: "wallet-rise 0.5s ease both",
      }}
    >
      {/* Glow orb */}
      <div
        className="absolute pointer-events-none"
        style={{
          width: 320,
          height: 320,
          borderRadius: "50%",
          background:
            "radial-gradient(circle, rgba(245,158,11,0.12) 0%, transparent 70%)",
          top: -80,
          right: -80,
        }}
      />
      {/* Accent lines */}
      <div className="absolute inset-0 pointer-events-none overflow-hidden rounded-2xl">
        <div
          style={{
            position: "absolute",
            top: 0,
            right: 60,
            width: 1,
            height: "100%",
            background:
              "linear-gradient(180deg, transparent, rgba(245,158,11,0.1), transparent)",
          }}
        />
        <div
          style={{
            position: "absolute",
            top: 40,
            left: 0,
            right: 0,
            height: 1,
            background:
              "linear-gradient(90deg, transparent, rgba(245,158,11,0.08), transparent)",
          }}
        />
      </div>

      {/* Header */}
      <div className="flex items-center gap-2 mb-5 relative z-10">
        <div
          className="w-8 h-8 rounded-xl flex items-center justify-center"
          style={{
            background: "rgba(245,158,11,0.15)",
            border: "1px solid rgba(245,158,11,0.25)",
          }}
        >
          <Wallet size={15} color="#f59e0b" strokeWidth={1.8} />
        </div>
        <span
          className="text-xs font-bold uppercase tracking-widest"
          style={{ color: "#f59e0b" }}
        >
          {t("wallet_myWallet")}
        </span>
        {balance?.channelName && (
          <span className="ml-auto text-[11px]" style={{ color: "#888" }}>
            {balance.channelName}
          </span>
        )}
      </div>

      {/* Balance grid */}
      <div className="grid grid-cols-2 gap-4 relative z-10">
        {/* Spendable coins */}
        <div
          className="rounded-xl p-4"
          style={{
            background: "rgba(245,158,11,0.06)",
            border: "1px solid rgba(245,158,11,0.12)",
            animation: "wallet-rise 0.5s ease both 0.1s",
          }}
        >
          <div className="flex items-center gap-1.5 mb-2">
            <Coins size={12} color="#f59e0b" strokeWidth={2} />
            <span
              className="text-[10px] font-semibold uppercase tracking-wider"
              style={{ color: "#f59e0b" }}
            >
              {t("wallet_balance")}
            </span>
          </div>
          {loading ? (
            <div
              className="h-8 w-24 rounded-lg animate-pulse"
              style={{ background: "rgba(245,158,11,0.1)" }}
            />
          ) : (
            <p
              className="text-3xl font-black tracking-tight"
              style={{
                color: "#fff",
                fontVariantNumeric: "tabular-nums",
                textShadow: "0 0 20px rgba(245,158,11,0.3)",
              }}
            >
              {formatCoins(balance?.walletBalance ?? 0)}
            </p>
          )}
          <p className="text-[10px] mt-1" style={{ color: "#666" }}>
            {t("wallet_availableCoins")}
          </p>
        </div>

        {/* Withdrawable amount */}
        <div
          className="rounded-xl p-4"
          style={{
            background: "rgba(16,185,129,0.06)",
            border: "1px solid rgba(16,185,129,0.12)",
            animation: "wallet-rise 0.5s ease both 0.15s",
          }}
        >
          <div className="flex items-center gap-1.5 mb-2">
            <ArrowDownToLine size={12} color="#10b981" strokeWidth={2} />
            <span
              className="text-[10px] font-semibold uppercase tracking-wider"
              style={{ color: "#10b981" }}
            >
              {t("wallet_withdrawal")}
            </span>
          </div>
          {loading ? (
            <div
              className="h-8 w-24 rounded-lg animate-pulse"
              style={{ background: "rgba(16,185,129,0.1)" }}
            />
          ) : (
            <p
              className="text-3xl font-black tracking-tight"
              style={{
                color: "#fff",
                fontVariantNumeric: "tabular-nums",
                textShadow: "0 0 20px rgba(16,185,129,0.3)",
              }}
            >
              {sym}
              {balance?.walletAmount?.toFixed(2) ?? "0.00"}
            </p>
          )}
          <p className="text-[10px] mt-1" style={{ color: "#666" }}>
            {t("wallet_withdrawableAmount")}
          </p>
        </div>
      </div>

      {/* Withdrawal request button */}
      <div className="relative z-10 mt-5 flex justify-center">
        <button
          onClick={onWithdraw}
          className="flex items-center gap-2 px-6 py-2.5 rounded-xl text-[13px] font-bold transition-all duration-200 active:scale-[0.97]"
          style={{
            background: "linear-gradient(135deg, #10b981, #059669)",
            color: "#fff",
            boxShadow: "0 4px 16px rgba(16,185,129,0.25)",
          }}
        >
          <ArrowDownToLine size={15} strokeWidth={2.2} />
          {t("wallet_withdrawalRequest")}
        </button>
      </div>

      {/* Coin watermark */}
      <div
        className="absolute bottom-4 right-6 text-[64px] font-black pointer-events-none select-none"
        style={{ color: "rgba(245,158,11,0.04)", lineHeight: 1 }}
      >
        ¢
      </div>
    </div>
  );
}

/* ── Withdrawal modal ───────────────────────────────────────────────────────── */

function WithdrawalModal({
  isOpen,
  onClose,
  onSuccess,
  prefillEmail,
  prefillName,
  minAmount,
  sym,
}: {
  isOpen: boolean;
  onClose: () => void;
  onSuccess: () => void;
  prefillEmail: string;
  prefillName: string;
  minAmount: number;
  sym: string;
}) {
  const { t } = useTranslation();
  const [amount, setAmount] = useState("");
  const [email, setEmail] = useState(prefillEmail);
  const [name, setName] = useState(prefillName);
  const [errors, setErrors] = useState<Record<string, string>>({});
  const [loading, setLoading] = useState(false);
  const [successMsg, setSuccessMsg] = useState("");

  useEffect(() => {
    if (isOpen) {
      setEmail(prefillEmail);
      setName(prefillName);
      setAmount("");
      setErrors({});
      setSuccessMsg("");
    }
  }, [isOpen, prefillEmail, prefillName]);

  const validate = () => {
    const errs: Record<string, string> = {};
    const num = parseFloat(amount);
    if (!amount || isNaN(num) || num <= 0)
      errs.amount = t("wallet_amountRequired");
    else if (minAmount > 0 && num < minAmount)
      errs.amount = `${t("wallet_amountTooLow")} (${sym}${minAmount})`;
    if (!email || !/^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(email))
      errs.email = t("wallet_paypalEmailRequired");
    if (!name || name.trim().length < 2 || !/^[a-zA-Z\s]+$/.test(name))
      errs.name = t("wallet_paypalNameRequired");
    return errs;
  };

  const handleSubmit = async () => {
    const errs = validate();
    if (Object.keys(errs).length) {
      setErrors(errs);
      return;
    }
    setLoading(true);
    setErrors({});
    try {
      await walletService.submitWithdrawal(amount, email, name);
      setSuccessMsg(t("wallet_withdrawalSuccess"));
      setTimeout(() => {
        onSuccess();
        onClose();
      }, 1800);
    } catch (err: unknown) {
      setErrors({
        submit:
          err instanceof Error ? err.message : "Failed to submit request.",
      });
    } finally {
      setLoading(false);
    }
  };

  if (!isOpen) return null;

  return (
    <div
      className="fixed inset-0 z-50 flex items-center justify-center p-4"
      style={{ background: "rgba(0,0,0,0.75)", backdropFilter: "blur(6px)" }}
    >
      <div
        className="w-full max-w-md rounded-2xl overflow-hidden"
        style={{
          background: "var(--card)",
          border: "1px solid var(--border)",
          boxShadow: "0 24px 80px rgba(0,0,0,0.6)",
        }}
      >
        {/* Modal header */}
        <div
          className="flex items-center justify-between px-6 py-4"
          style={{ borderBottom: "1px solid var(--border-soft)" }}
        >
          <div className="flex items-center gap-2">
            <div
              className="w-7 h-7 rounded-lg flex items-center justify-center"
              style={{
                background: "rgba(16,185,129,0.12)",
                border: "1px solid rgba(16,185,129,0.2)",
              }}
            >
              <ArrowDownToLine size={14} color="#10b981" strokeWidth={2} />
            </div>
            <span
              className="text-sm font-bold"
              style={{ color: "var(--text-primary)" }}
            >
              {t("wallet_withdrawalRequest")}
            </span>
          </div>
          <button
            onClick={onClose}
            className="w-7 h-7 flex items-center justify-center rounded-lg transition-colors"
            style={{ color: "var(--text-muted)" }}
            onMouseEnter={(e) =>
              (e.currentTarget.style.background = "var(--btn-ghost-hover)")
            }
            onMouseLeave={(e) =>
              (e.currentTarget.style.background = "transparent")
            }
          >
            <X size={15} strokeWidth={2} />
          </button>
        </div>

        {/* Modal body */}
        <div className="px-6 py-5 flex flex-col gap-4">
          {minAmount > 0 && (
            <div
              className="flex items-center gap-2 px-3 py-2 rounded-lg text-[11px]"
              style={{
                background: "rgba(245,158,11,0.06)",
                border: "1px solid rgba(245,158,11,0.12)",
                color: "#f59e0b",
              }}
            >
              <Coins size={12} strokeWidth={2} />
              {t("wallet_minWithdrawal")}: {sym}
              {minAmount}
            </div>
          )}

          {/* Amount */}
          <div className="flex flex-col gap-1.5">
            <label
              className="text-[11px] font-semibold uppercase tracking-wide"
              style={{ color: "var(--text-muted)" }}
            >
              {t("wallet_withdrawalAmount")}
            </label>
            <div
              className="flex items-center rounded-xl overflow-hidden"
              style={{
                border: `1.5px solid ${errors.amount ? "#ef4444" : "var(--border)"}`,
                background: "var(--deep)",
              }}
            >
              <span
                className="px-3 text-sm font-bold"
                style={{ color: "#10b981" }}
              >
                {sym}
              </span>
              <input
                type="number"
                value={amount}
                onChange={(e) => {
                  setAmount(e.target.value);
                  setErrors((p) => ({ ...p, amount: "" }));
                }}
                placeholder={t("wallet_enterAmount")}
                className="flex-1 bg-transparent py-3 pr-4 text-sm outline-none"
                style={{ color: "var(--text-primary)" }}
              />
            </div>
            {errors.amount && (
              <p className="text-[11px]" style={{ color: "#ef4444" }}>
                {errors.amount}
              </p>
            )}
          </div>

          {/* PayPal Email */}
          <div className="flex flex-col gap-1.5">
            <label
              className="text-[11px] font-semibold uppercase tracking-wide"
              style={{ color: "var(--text-muted)" }}
            >
              {t("wallet_paypalEmail")}
            </label>
            <input
              type="email"
              value={email}
              onChange={(e) => {
                setEmail(e.target.value);
                setErrors((p) => ({ ...p, email: "" }));
              }}
              placeholder={t("wallet_enterPaypalEmail")}
              className="rounded-xl px-4 py-3 text-sm outline-none"
              style={{
                background: "var(--deep)",
                border: `1.5px solid ${errors.email ? "#ef4444" : "var(--border)"}`,
                color: "var(--text-primary)",
              }}
            />
            {errors.email && (
              <p className="text-[11px]" style={{ color: "#ef4444" }}>
                {errors.email}
              </p>
            )}
          </div>

          {/* PayPal Name */}
          <div className="flex flex-col gap-1.5">
            <label
              className="text-[11px] font-semibold uppercase tracking-wide"
              style={{ color: "var(--text-muted)" }}
            >
              {t("wallet_paypalName")}
            </label>
            <input
              type="text"
              value={name}
              onChange={(e) => {
                setName(e.target.value);
                setErrors((p) => ({ ...p, name: "" }));
              }}
              placeholder={t("wallet_enterPaypalName")}
              className="rounded-xl px-4 py-3 text-sm outline-none"
              style={{
                background: "var(--deep)",
                border: `1.5px solid ${errors.name ? "#ef4444" : "var(--border)"}`,
                color: "var(--text-primary)",
              }}
            />
            {errors.name && (
              <p className="text-[11px]" style={{ color: "#ef4444" }}>
                {errors.name}
              </p>
            )}
          </div>

          {errors.submit && (
            <p
              className="text-[12px] px-3 py-2 rounded-lg"
              style={{
                background: "rgba(239,68,68,0.08)",
                color: "#ef4444",
                border: "1px solid rgba(239,68,68,0.15)",
              }}
            >
              {errors.submit}
            </p>
          )}

          {successMsg && (
            <p
              className="text-[12px] px-3 py-2 rounded-lg flex items-center gap-2"
              style={{
                background: "rgba(16,185,129,0.08)",
                color: "#10b981",
                border: "1px solid rgba(16,185,129,0.15)",
              }}
            >
              <CheckCircle2 size={13} strokeWidth={2} /> {successMsg}
            </p>
          )}
        </div>

        {/* Modal footer */}
        <div className="px-6 pb-5">
          <button
            onClick={handleSubmit}
            disabled={loading}
            className="w-full py-3 rounded-xl text-[13px] font-black tracking-wide text-white transition-all duration-150 active:scale-[0.98] disabled:opacity-60 flex items-center justify-center gap-2"
            style={{
              background: "linear-gradient(135deg, #10b981, #059669)",
              boxShadow: "0 4px 16px rgba(16,185,129,0.25)",
            }}
          >
            {loading && <Loader2 size={14} className="animate-spin" />}
            {t("wallet_submitWithdrawal")}
          </button>
        </div>
      </div>
    </div>
  );
}

/* ── Package card ───────────────────────────────────────────────────────────── */

function PackageCard({
  pkg,
  isBest,
  index,
  onBuy,
  sym,
}: {
  pkg: CoinPackage;
  isBest: boolean;
  index: number;
  onBuy: (pkg: CoinPackage) => void;
  sym: string;
}) {
  const [hovered, setHovered] = useState(false);
  const { t } = useTranslation();
  const cpd = coinsPerDollar(pkg);

  return (
    <div
      className="relative flex flex-col rounded-2xl overflow-hidden cursor-pointer transition-all duration-250"
      style={{
        background: isBest
          ? "linear-gradient(145deg, #1c1400, #12100a)"
          : "var(--card)",
        border: `1px solid ${isBest ? "rgba(245,158,11,0.35)" : hovered ? "rgba(245,158,11,0.2)" : "var(--border)"}`,
        boxShadow: isBest
          ? "0 0 40px rgba(245,158,11,0.12), 0 8px 32px rgba(0,0,0,0.4)"
          : hovered
            ? "0 8px 28px rgba(245,158,11,0.08), 0 4px 16px rgba(0,0,0,0.3)"
            : "0 2px 12px rgba(0,0,0,0.2)",
        transform: hovered
          ? "translateY(-3px)"
          : isBest
            ? "translateY(-1px)"
            : "none",
        animation: `wallet-card-in 0.45s ease both`,
        animationDelay: `${index * 80}ms`,
      }}
      onMouseEnter={() => setHovered(true)}
      onMouseLeave={() => setHovered(false)}
    >
      {isBest && (
        <div
          className="absolute top-0 left-0 right-0 flex items-center justify-center gap-1 py-1.5 z-10"
          style={{
            background: "rgba(245,158,11,0.15)",
            borderBottom: "1px solid rgba(245,158,11,0.2)",
          }}
        >
          <Star size={10} color="#f59e0b" fill="#f59e0b" />
          <span
            className="text-[9px] font-black uppercase tracking-widest"
            style={{ color: "#f59e0b" }}
          >
            {t("wallet_bestValue")}
          </span>
          <Star size={10} color="#f59e0b" fill="#f59e0b" />
        </div>
      )}

      <div
        className="relative w-full flex items-center justify-center"
        style={{
          height: 120,
          background: isBest
            ? "linear-gradient(135deg, rgba(245,158,11,0.1), rgba(245,158,11,0.03))"
            : "var(--border-soft)",
          marginTop: isBest ? 30 : 0,
        }}
      >
        {pkg.image ? (
          <Image
            src={pkg.image}
            alt={pkg.name}
            width={80}
            height={80}
            className="object-contain"
            unoptimized
            style={{
              filter: hovered
                ? "drop-shadow(0 0 12px rgba(245,158,11,0.4))"
                : "none",
              transition: "filter 0.3s ease, transform 0.3s ease",
              transform: hovered ? "scale(1.05)" : "scale(1)",
            }}
          />
        ) : (
          <div
            className="w-16 h-16 rounded-full flex items-center justify-center"
            style={{
              background: "rgba(245,158,11,0.1)",
              border: "2px solid rgba(245,158,11,0.2)",
            }}
          >
            <Coins size={28} color="#f59e0b" strokeWidth={1.5} />
          </div>
        )}
        {hovered && (
          <div
            className="absolute inset-0 pointer-events-none"
            style={{
              background:
                "linear-gradient(105deg, transparent 30%, rgba(245,158,11,0.06) 50%, transparent 70%)",
              animation: "wallet-shimmer 1.5s ease infinite",
            }}
          />
        )}
      </div>

      <div className="p-4 flex flex-col gap-3 flex-1">
        <div className="text-center">
          <p
            className="text-2xl font-black tracking-tight"
            style={{ color: isBest ? "#f59e0b" : "var(--text-muted)" }}
          >
            {formatCoins(pkg.coin)}
          </p>
          <p
            className="text-[10px] font-semibold uppercase tracking-wider mt-0.5"
            style={{ color: "#666" }}
          >
            {t("wallet_coins")}
          </p>
        </div>

        <div
          className="flex items-center justify-center gap-1.5 py-1.5 rounded-lg"
          style={{
            background: "rgba(245,158,11,0.06)",
            border: "1px solid rgba(245,158,11,0.1)",
          }}
        >
          <Zap size={10} color="#f59e0b" fill="#f59e0b" />
          <span className="text-[10px] font-bold" style={{ color: "#f59e0b" }}>
            {cpd.toLocaleString()} coins/{sym}1
          </span>
        </div>

        <div className="flex flex-col gap-1.5">
          {[
            t("wallet_instantDelivery"),
            t("wallet_noExpiry"),
            pkg.coin >= 5000 ? t("wallet_bonus2p") : null,
          ]
            .filter(Boolean)
            .map((feat, i) => (
              <div key={i} className="flex items-center gap-1.5">
                <ShieldCheck size={10} color="#10b981" strokeWidth={2} />
                <span className="text-[10px]" style={{ color: "#888" }}>
                  {feat}
                </span>
              </div>
            ))}
        </div>

        <div className="mt-auto pt-1">
          <button
            onClick={() => onBuy(pkg)}
            className="w-full h-10 rounded-xl text-[12px] font-black transition-all duration-200 active:scale-95 flex items-center justify-center gap-2"
            style={{
              background: isBest
                ? "linear-gradient(135deg, #f59e0b, #d97706)"
                : hovered
                  ? "rgba(245,158,11,0.15)"
                  : "var(--btn-ghost)",
              color: isBest ? "#000" : "var(--text-muted)",
              border: isBest ? "none" : "1px solid rgba(245,158,11,0.2)",
              boxShadow: isBest ? "0 4px 16px rgba(245,158,11,0.3)" : "none",
            }}
          >
            <span>
              {sym}
              {pkg.price}
            </span>
            <span style={{ opacity: 0.7, fontSize: 10 }}>·</span>
            <Coins size={12} strokeWidth={2} />
            <span>{formatCoins(pkg.coin)}</span>
          </button>
        </div>
      </div>
    </div>
  );
}

/* ── Package skeleton ───────────────────────────────────────────────────────── */

function PackageSkeleton() {
  return (
    <div
      className="rounded-2xl overflow-hidden animate-pulse"
      style={{
        background: "var(--card)",
        border: "1px solid var(--border-soft)",
      }}
    >
      <div
        className="h-28 w-full"
        style={{ background: "var(--border-soft)" }}
      />
      <div className="p-4 flex flex-col gap-3">
        <div
          className="h-6 rounded-lg mx-auto"
          style={{ background: "var(--border)", width: "50%" }}
        />
        <div
          className="h-3 rounded-full mx-auto"
          style={{ background: "var(--border-soft)", width: "70%" }}
        />
        <div
          className="h-7 rounded-lg"
          style={{ background: "var(--btn-ghost)" }}
        />
        <div
          className="h-8 rounded-xl mt-1"
          style={{ background: "var(--border-soft)" }}
        />
      </div>
    </div>
  );
}

/* ── Transaction list skeleton ──────────────────────────────────────────────── */

function TxSkeleton() {
  return (
    <div
      className="flex flex-col divide-y"
      style={{ borderColor: "var(--border-soft)" }}
    >
      {Array.from({ length: 3 }).map((_, i) => (
        <div
          key={i}
          className="flex items-center gap-3 px-4 py-3 animate-pulse"
        >
          <div
            className="w-9 h-9 rounded-full flex-shrink-0"
            style={{ background: "var(--btn-ghost)" }}
          />
          <div className="flex-1 space-y-1.5">
            <div
              className="h-2.5 rounded-full"
              style={{ background: "var(--btn-ghost)", width: "55%" }}
            />
            <div
              className="h-2 rounded-full"
              style={{ background: "var(--border-soft)", width: "35%" }}
            />
          </div>
          <div
            className="h-4 w-14 rounded"
            style={{ background: "var(--btn-ghost)" }}
          />
        </div>
      ))}
    </div>
  );
}

/* ── Empty state ────────────────────────────────────────────────────────────── */

function EmptyState({
  icon: Icon,
  label,
}: {
  icon: React.ElementType;
  label: string;
}) {
  return (
    <div className="flex flex-col items-center py-12 gap-2">
      <Icon size={24} color="#444" strokeWidth={1.3} />
      <p className="text-[11px]" style={{ color: "#555" }}>
        {label}
      </p>
    </div>
  );
}

/* ── Main page ──────────────────────────────────────────────────────────────── */

export default function WalletPage() {
  const { t } = useTranslation();
  const { settings } = useGeneralSettings();
  const sym = settings?.currencySymbol ?? "$";
  const minAmount = settings?.minWithdrawalAmount ?? 0;

  const [balance, setBalance] = useState<WalletBalance | null>(null);
  const [packages, setPackages] = useState<CoinPackage[]>([]);
  const [balanceLoading, setBalanceLoading] = useState(true);
  const [packagesLoading, setPackagesLoading] = useState(true);
  const [error, setError] = useState("");
  const [payCtx, setPayCtx] = useState<PaymentContext | null>(null);
  const [txTab, setTxTab] = useState<TxTab>("purchases");
  const [showWithdrawalModal, setShowWithdrawalModal] = useState(false);

  // --- purchases tab ---
  const [purchases, setPurchases] = useState<CoinPurchaseTransaction[]>([]);
  const [purchasesLoading, setPurchasesLoading] = useState(false);
  const [purchasesPage, setPurchasesPage] = useState(1);
  const [purchasesHasMore, setPurchasesHasMore] = useState(false);
  const [purchasesLoadingMore, setPurchasesLoadingMore] = useState(false);

  // --- withdrawals tab ---
  const [withdrawals, setWithdrawals] = useState<WithdrawalTransaction[]>([]);
  const [withdrawalsLoading, setWithdrawalsLoading] = useState(false);
  const [withdrawalsPage, setWithdrawalsPage] = useState(1);
  const [withdrawalsHasMore, setWithdrawalsHasMore] = useState(false);
  const [withdrawalsLoadingMore, setWithdrawalsLoadingMore] = useState(false);

  // --- gifts tab ---
  const [gifts, setGifts] = useState<GiftTransaction[]>([]);
  const [giftsLoading, setGiftsLoading] = useState(false);
  const [giftsPage, setGiftsPage] = useState(1);
  const [giftsHasMore, setGiftsHasMore] = useState(false);
  const [giftsLoadingMore, setGiftsLoadingMore] = useState(false);

  const loadBalance = useCallback(() => {
    setBalanceLoading(true);
    walletService
      .getBalance()
      .then(setBalance)
      .catch(() => setError("Failed to load wallet balance."))
      .finally(() => setBalanceLoading(false));
  }, []);

  const loadPackages = useCallback(() => {
    walletService
      .getCoinPackages()
      .then(setPackages)
      .catch(() => {})
      .finally(() => setPackagesLoading(false));
  }, []);

  const loadPurchases = useCallback(async (page: number, append = false) => {
    if (page === 1) setPurchasesLoading(true);
    else setPurchasesLoadingMore(true);
    try {
      const res = await walletService.getCoinTransactions(page);
      setPurchases((prev) => (append ? [...prev, ...res.items] : res.items));
      setPurchasesPage(res.currentPage);
      setPurchasesHasMore(res.hasMore);
    } catch {
      /* ignore */
    } finally {
      setPurchasesLoading(false);
      setPurchasesLoadingMore(false);
    }
  }, []);

  const loadWithdrawals = useCallback(async (page: number, append = false) => {
    if (page === 1) setWithdrawalsLoading(true);
    else setWithdrawalsLoadingMore(true);
    try {
      const res = await walletService.getWithdrawalTransactions(page);
      setWithdrawals((prev) => (append ? [...prev, ...res.items] : res.items));
      setWithdrawalsPage(res.currentPage);
      setWithdrawalsHasMore(res.hasMore);
    } catch {
      /* ignore */
    } finally {
      setWithdrawalsLoading(false);
      setWithdrawalsLoadingMore(false);
    }
  }, []);

  const loadGifts = useCallback(async (page: number, append = false) => {
    if (page === 1) setGiftsLoading(true);
    else setGiftsLoadingMore(true);
    try {
      const res = await walletService.getGiftTransactions(page);
      setGifts((prev) => (append ? [...prev, ...res.items] : res.items));
      setGiftsPage(res.currentPage);
      setGiftsHasMore(res.hasMore);
    } catch {
      /* ignore */
    } finally {
      setGiftsLoading(false);
      setGiftsLoadingMore(false);
    }
  }, []);

  // Load everything on mount
  useEffect(() => {
    loadBalance();
    loadPackages();
    loadPurchases(1);
  }, [loadBalance, loadPackages, loadPurchases]);

  // Lazy load tabs on first switch
  useEffect(() => {
    if (
      txTab === "withdrawals" &&
      withdrawals.length === 0 &&
      !withdrawalsLoading
    ) {
      loadWithdrawals(1);
    }
    if (txTab === "gifts" && gifts.length === 0 && !giftsLoading) {
      loadGifts(1);
    }
  }, [
    txTab,
    withdrawals.length,
    gifts.length,
    withdrawalsLoading,
    giftsLoading,
    loadWithdrawals,
    loadGifts,
  ]);

  const best = bestValueId(packages);

  const TABS: { key: TxTab; label: string; count: number }[] = [
    {
      key: "purchases",
      label: t("wallet_tabPurchases"),
      count: purchases.length,
    },
    {
      key: "withdrawals",
      label: t("wallet_tabWithdrawals"),
      count: withdrawals.length,
    },
    { key: "gifts", label: t("wallet_tabGifts"), count: gifts.length },
  ];

  return (
    <>
      <style>{`
        @keyframes wallet-rise { from { opacity:0; transform:translateY(14px); } to { opacity:1; transform:none; } }
        @keyframes wallet-card-in { from { opacity:0; transform:translateY(20px) scale(0.97); } to { opacity:1; transform:none; } }
        @keyframes wallet-shimmer { 0%,100%{opacity:0} 50%{opacity:1} }
      `}</style>

      <div
        className="min-h-screen px-4 py-6 pb-28 md:px-6"
        style={{ background: "var(--bg)" }}
      >
        <div className="mx-auto flex flex-col gap-6">
          {/* Page title */}
          <div style={{ animation: "wallet-rise 0.35s ease both" }}>
            <h1
              className="text-lg font-black tracking-tight"
              style={{ letterSpacing: "-0.02em", color: "var(--text-primary)" }}
            >
              {t("wallet_title")}
            </h1>
            <p className="text-[11px] mt-0.5" style={{ color: "#555" }}>
              {t("wallet_subtitle")}
            </p>
          </div>

          {/* Balance card */}
          {error ? (
            <div
              className="rounded-xl px-4 py-3 text-[12px]"
              style={{
                background: "rgba(244,63,94,0.08)",
                color: "#f43f5e",
                border: "1px solid rgba(244,63,94,0.15)",
              }}
            >
              {error}
            </div>
          ) : (
            <BalanceHero
              balance={balance}
              loading={balanceLoading}
              sym={sym}
              onWithdraw={() => setShowWithdrawalModal(true)}
            />
          )}

          {/* Buy coins section */}
          <div style={{ animation: "wallet-rise 0.5s ease both 0.1s" }}>
            <div className="flex items-center gap-3 mb-4">
              <div
                className="w-7 h-7 rounded-lg flex items-center justify-center flex-shrink-0"
                style={{
                  background: "rgba(245,158,11,0.1)",
                  border: "1px solid rgba(245,158,11,0.18)",
                }}
              >
                <Coins size={13} color="#f59e0b" strokeWidth={2} />
              </div>
              <h2
                className="text-sm font-bold"
                style={{ color: "var(--text-primary)" }}
              >
                {t("wallet_buyCoins")}
              </h2>
              <div
                className="flex-1 h-px"
                style={{ background: "var(--border-soft)" }}
              />
            </div>
            <div className="grid grid-cols-1 sm:grid-cols-3 gap-4">
              {packagesLoading
                ? Array.from({ length: 3 }).map((_, i) => (
                    <PackageSkeleton key={i} />
                  ))
                : packages.map((pkg, i) => (
                    <PackageCard
                      key={pkg.id}
                      pkg={pkg}
                      isBest={pkg.id === best}
                      index={i}
                      onBuy={(p) =>
                        setPayCtx({
                          type: "coin",
                          packageId: String(p.id),
                          packageName: p.name,
                          price: p.price,
                          coin: p.coin,
                        })
                      }
                      sym={sym}
                    />
                  ))}
            </div>
          </div>

          {/* Info strip */}
          <div
            className="rounded-xl px-4 py-3 flex items-center gap-3"
            style={{
              background: "var(--btn-ghost)",
              border: "1px solid var(--border-soft)",
              animation: "wallet-rise 0.55s ease both 0.15s",
            }}
          >
            <ShieldCheck size={16} color="#10b981" strokeWidth={1.8} />
            <p
              className="text-[11px] leading-relaxed"
              style={{ color: "#666" }}
            >
              {t("wallet_disclaimer")}
            </p>
          </div>

          {/* Transaction history */}
          <div style={{ animation: "wallet-rise 0.6s ease both 0.2s" }}>
            <div className="flex items-center gap-3 mb-3">
              <div
                className="w-7 h-7 rounded-lg flex items-center justify-center flex-shrink-0"
                style={{
                  background: "var(--btn-ghost)",
                  border: "1px solid var(--btn-ghost-hover)",
                }}
              >
                <Receipt size={13} color="#888" strokeWidth={2} />
              </div>
              <h2
                className="text-sm font-bold"
                style={{ color: "var(--text-primary)" }}
              >
                {t("wallet_txHistory")}
              </h2>
              <div
                className="flex-1 h-px"
                style={{ background: "var(--border-soft)" }}
              />
            </div>

            {/* Tabs */}
            <div className="flex gap-2 mb-3 flex-wrap">
              {TABS.map((tab) => (
                <button
                  key={tab.key}
                  onClick={() => setTxTab(tab.key)}
                  className="px-3 py-1.5 rounded-lg text-[11px] font-semibold transition-all"
                  style={{
                    background:
                      txTab === tab.key
                        ? "rgba(245,158,11,0.12)"
                        : "var(--border-soft)",
                    color: txTab === tab.key ? "#f59e0b" : "#777",
                    border: `1px solid ${txTab === tab.key ? "rgba(245,158,11,0.2)" : "var(--border)"}`,
                  }}
                >
                  {tab.label}
                  {tab.count > 0 ? ` (${tab.count})` : ""}
                </button>
              ))}
            </div>

            {/* List panel */}
            <div
              className="rounded-xl overflow-hidden"
              style={{
                background: "var(--card)",
                border: "1px solid var(--border-soft)",
              }}
            >
              {/* ─ Purchases ─ */}
              {txTab === "purchases" &&
                (purchasesLoading ? (
                  <TxSkeleton />
                ) : purchases.length === 0 ? (
                  <EmptyState icon={Coins} label={t("wallet_noPurchases")} />
                ) : (
                  <div
                    className="flex flex-col divide-y"
                    style={{ borderColor: "var(--border-soft)" }}
                  >
                    {purchases.map((tx) => (
                      <div
                        key={tx.id}
                        className="flex items-center gap-3 px-4 py-3"
                      >
                        <div
                          className="w-9 h-9 rounded-full flex-shrink-0 flex items-center justify-center"
                          style={{ background: "rgba(245,158,11,0.1)" }}
                        >
                          <Coins size={15} color="#f59e0b" strokeWidth={1.8} />
                        </div>
                        <div className="flex-1 min-w-0">
                          <p
                            className="text-[12px] font-semibold"
                            style={{ color: "var(--text-primary)" }}
                          >
                            {tx.coin.toLocaleString()} {t("wallet_coins")}
                          </p>
                          <p className="text-[10px]" style={{ color: "#666" }}>
                            {tx.createdAt}
                          </p>
                        </div>
                        <div className="text-right flex-shrink-0">
                          <p
                            className="text-[12px] font-bold"
                            style={{ color: "var(--text-primary)" }}
                          >
                            {sym}
                            {tx.price}
                          </p>
                          <StatusBadge status={tx.status} />
                        </div>
                      </div>
                    ))}
                  </div>
                ))}

              {/* ─ Withdrawals ─ */}
              {txTab === "withdrawals" &&
                (withdrawalsLoading ? (
                  <TxSkeleton />
                ) : withdrawals.length === 0 ? (
                  <EmptyState
                    icon={ArrowDownToLine}
                    label={t("wallet_noWithdrawals")}
                  />
                ) : (
                  <div
                    className="flex flex-col divide-y"
                    style={{ borderColor: "var(--border-soft)" }}
                  >
                    {withdrawals.map((tx) => (
                      <div
                        key={tx.id}
                        className="flex items-center gap-3 px-4 py-3"
                      >
                        <div
                          className="w-9 h-9 rounded-full flex-shrink-0 flex items-center justify-center"
                          style={{ background: "rgba(16,185,129,0.1)" }}
                        >
                          <ArrowDownToLine
                            size={15}
                            color="#10b981"
                            strokeWidth={1.8}
                          />
                        </div>
                        <div className="flex-1 min-w-0">
                          <p
                            className="text-[12px] font-semibold"
                            style={{ color: "var(--text-primary)" }}
                          >
                            {sym}
                            {tx.amount}
                          </p>
                          <p
                            className="text-[10px] truncate"
                            style={{ color: "#666" }}
                          >
                            {tx.paymentType} · {tx.createdAt}
                          </p>
                        </div>
                        <div className="text-right flex-shrink-0">
                          <StatusBadge status={tx.status} />
                        </div>
                      </div>
                    ))}
                  </div>
                ))}

              {/* ─ Gifts ─ */}
              {txTab === "gifts" &&
                (giftsLoading ? (
                  <TxSkeleton />
                ) : gifts.length === 0 ? (
                  <EmptyState icon={Gift} label={t("wallet_noGifts")} />
                ) : (
                  <div
                    className="flex flex-col divide-y"
                    style={{ borderColor: "var(--border-soft)" }}
                  >
                    {gifts.map((tx) => (
                      <div
                        key={tx.id}
                        className="flex items-center gap-3 px-4 py-3"
                      >
                        <div
                          className="w-9 h-9 rounded-full flex-shrink-0 flex items-center justify-center"
                          style={{ background: "rgba(168,85,247,0.1)" }}
                        >
                          <Gift size={15} color="#a855f7" strokeWidth={1.8} />
                        </div>
                        <div className="flex-1 min-w-0">
                          <p
                            className="text-[12px] font-semibold truncate"
                            style={{ color: "var(--text-primary)" }}
                          >
                            {tx.giftName}
                          </p>
                          <p
                            className="text-[10px] truncate"
                            style={{ color: "#666" }}
                          >
                            {t("wallet_giftTo")} {tx.channelName} ·{" "}
                            {tx.createdAt}
                          </p>
                          {tx.contentName && (
                            <p
                              className="text-[10px] truncate"
                              style={{ color: "#555" }}
                            >
                              {t("wallet_for")} {tx.contentName}
                            </p>
                          )}
                        </div>
                        <div className="text-right flex-shrink-0 flex flex-col items-end gap-1">
                          <div className="flex items-center gap-1">
                            <Coins size={11} color="#f59e0b" strokeWidth={2} />
                            <span
                              className="text-[12px] font-bold"
                              style={{ color: "#f59e0b" }}
                            >
                              {tx.price}
                            </span>
                          </div>
                          <StatusBadge status={tx.status} />
                        </div>
                      </div>
                    ))}
                  </div>
                ))}

              {/* Load more */}
              {((txTab === "purchases" && purchasesHasMore) ||
                (txTab === "withdrawals" && withdrawalsHasMore) ||
                (txTab === "gifts" && giftsHasMore)) && (
                <div
                  className="px-4 py-3 flex justify-center"
                  style={{ borderTop: "1px solid var(--border-soft)" }}
                >
                  <button
                    onClick={() => {
                      if (txTab === "purchases")
                        loadPurchases(purchasesPage + 1, true);
                      if (txTab === "withdrawals")
                        loadWithdrawals(withdrawalsPage + 1, true);
                      if (txTab === "gifts") loadGifts(giftsPage + 1, true);
                    }}
                    disabled={
                      purchasesLoadingMore ||
                      withdrawalsLoadingMore ||
                      giftsLoadingMore
                    }
                    className="flex items-center gap-2 px-4 py-2 rounded-lg text-[11px] font-semibold transition-all active:scale-95 disabled:opacity-50"
                    style={{
                      background: "var(--btn-ghost)",
                      border: "1px solid var(--border)",
                      color: "var(--text-muted)",
                    }}
                  >
                    {purchasesLoadingMore ||
                    withdrawalsLoadingMore ||
                    giftsLoadingMore ? (
                      <Loader2 size={12} className="animate-spin" />
                    ) : (
                      <ChevronDown size={12} strokeWidth={2} />
                    )}
                    {t("wallet_loadMore")}
                  </button>
                </div>
              )}
            </div>
          </div>
        </div>
      </div>

      <PaymentModal
        context={payCtx}
        onClose={() => setPayCtx(null)}
        onSuccess={() => {
          setPayCtx(null);
          loadBalance();
          loadPurchases(1);
        }}
      />

      <WithdrawalModal
        isOpen={showWithdrawalModal}
        onClose={() => setShowWithdrawalModal(false)}
        onSuccess={() => {
          loadBalance();
          loadWithdrawals(1);
        }}
        prefillEmail={balance?.paypalEmail ?? ""}
        prefillName={balance?.paypalName ?? ""}
        minAmount={minAmount}
        sym={sym}
      />
    </>
  );
}
