"use client";

import { useCallback, useEffect, useMemo, useState } from "react";
import { useRouter } from "next/navigation";
import toast from "react-hot-toast";
import Link from "next/link";

import DashboardSidebar from "@/app/components/astrologer/DashboardSidebar";
import NotificationBell from "@/app/components/notifications/NotificationBell";
import {
  getAstrologerWallet,
  getAstrologerWalletTransactions,
  getAstrologerWalletWithdrawHistory,
  AstrologerWalletWithdrawHistory,
  AstrologerWalletTransaction,
  AstrologerWalletSummary,
} from "@/app/lib/astrologer";

type TransactionTab = "ALL" | "EARNINGS" | "WITHDRAWALS";
type DateFilter = "TODAY" | "WEEK" | "MONTH" | "ALL";

function formatMoney(value: number | string | null | undefined) {
  const amount = Number(value ?? 0);
  if (!Number.isFinite(amount)) return "₹0";
  return `₹${Math.round(amount).toLocaleString("en-IN")}`;
}

function getTransactionDate(tx: AstrologerWalletTransaction | AstrologerWalletWithdrawHistory) {
  // Transactions API returns date and time as separate fields.
  if ("transactionDate" in tx && tx.transactionDate) {
    return `${tx.transactionDate}${tx.transactionTime ? ` ${tx.transactionTime}` : ""}`;
  }

  if ("requestDate" in tx && tx.requestDate) return tx.requestDate;

  return (
    tx.date ??
    tx.createdAt ??
    tx.created_at ??
    tx.transaction_date ??
    tx.updatedAt ??
    tx.updated_at ??
    ""
  );
}

function parseWalletDate(value: string) {
  if (!value) return null;

  // Handles API formats such as:
  // "04 Sep 2026", "04 Sep 2026 08:14 PM", "10 Sep 2026 01:02 PM".
  const match = value.trim().match(
    /^(\d{1,2})\s+([A-Za-z]{3,9})\s+(\d{4})(?:\s+(\d{1,2}):(\d{2})(?:\s*(AM|PM))?)?$/i
  );

  if (match) {
    const [, day, monthText, year, hourText, minuteText, meridiem] = match;
    const months: Record<string, number> = {
      jan: 0, january: 0,
      feb: 1, february: 1,
      mar: 2, march: 2,
      apr: 3, april: 3,
      may: 4,
      jun: 5, june: 5,
      jul: 6, july: 6,
      aug: 7, august: 7,
      sep: 8, sept: 8, september: 8,
      oct: 9, october: 9,
      nov: 10, november: 10,
      dec: 11, december: 11,
    };

    const month = months[monthText.toLowerCase()];
    if (month !== undefined) {
      let hour = hourText ? Number(hourText) : 0;
      const minute = minuteText ? Number(minuteText) : 0;

      if (meridiem) {
        const upper = meridiem.toUpperCase();
        if (upper === "PM" && hour !== 12) hour += 12;
        if (upper === "AM" && hour === 12) hour = 0;
      }

      const parsed = new Date(Number(year), month, Number(day), hour, minute, 0, 0);
      if (!Number.isNaN(parsed.getTime())) return parsed;
    }
  }

  const fallback = new Date(value);
  return Number.isNaN(fallback.getTime()) ? null : fallback;
}

function getTransactionAmount(tx: AstrologerWalletTransaction | AstrologerWalletWithdrawHistory) {
  return Number(
    tx.amount ??
      tx.transactionAmount ??
      tx.transaction_amount ??
      tx.value ??
      0
  );
}

function getTransactionDescription(tx: AstrologerWalletTransaction | AstrologerWalletWithdrawHistory) {
  return (
    tx.description ??
    tx.title ??
    tx.name ??
    ("paymentMethod" in tx ? "Withdrawal to Bank" : undefined) ??
    tx.transactionType ??
    tx.transaction_type ??
    "Wallet Transaction"
  );
}

function getTransactionType(tx: AstrologerWalletTransaction | AstrologerWalletWithdrawHistory) {
  return String(
    tx.type ??
      tx.transactionType ??
      tx.transaction_type ??
      tx.category ??
      ""
  ).toUpperCase();
}

function isWithdrawal(tx: AstrologerWalletTransaction | AstrologerWalletWithdrawHistory) {
  if ("requestDate" in tx || "paymentMethod" in tx) return true;

  const type = getTransactionType(tx);
  const text = getTransactionDescription(tx).toLowerCase();
  return (
    type.includes("WITHDRAW") ||
    type.includes("DEBIT") ||
    text.includes("withdraw") ||
    getTransactionAmount(tx) < 0
  );
}

function isEarning(tx: AstrologerWalletTransaction | AstrologerWalletWithdrawHistory) {
  if (isWithdrawal(tx)) return false;
  const type = getTransactionType(tx);
  const text = getTransactionDescription(tx).toLowerCase();
  return (
    type.includes("EARN") ||
    type.includes("CREDIT") ||
    type.includes("CONSULT") ||
    text.includes("consult") ||
    getTransactionAmount(tx) >= 0
  );
}

function formatDateTime(value: string) {
  if (!value) return "--";

  const date = parseWalletDate(value);
  if (!date) return value;

  return date.toLocaleString("en-IN", {
    day: "2-digit",
    month: "short",
    year: "numeric",
    hour: "2-digit",
    minute: "2-digit",
  });
}

function isInDateRange(value: string, filter: DateFilter) {
  if (filter === "ALL" || !value) return true;

  const date = parseWalletDate(value);
  if (!date) return false;

  const now = new Date();

  if (filter === "TODAY") {
    const start = new Date(now.getFullYear(), now.getMonth(), now.getDate());
    const end = new Date(start);
    end.setDate(end.getDate() + 1);
    return date >= start && date < end;
  }

  if (filter === "WEEK") {
    const start = new Date(now);
    start.setHours(0, 0, 0, 0);
    const day = start.getDay();
    start.setDate(start.getDate() - (day === 0 ? 6 : day - 1));

    const end = new Date(start);
    end.setDate(end.getDate() + 7);
    return date >= start && date < end;
  }

  const start = new Date(now.getFullYear(), now.getMonth(), 1);
  const end = new Date(now.getFullYear(), now.getMonth() + 1, 1);
  return date >= start && date < end;
}

function Icon({
  name,
  size = 22,
}: {
  name:
    | "chart"
    | "calendar"
    | "rank"
    | "wallet"
    | "bank"
    | "refresh"
    | "bag"
    | "info"
    | "clock"
    | "arrow-up"
    | "arrow-down"
    | "chevron";
  size?: number;
}) {
  const common = {
    width: size,
    height: size,
    viewBox: "0 0 24 24",
    fill: "none",
    stroke: "currentColor",
    strokeWidth: 1.8,
    strokeLinecap: "round" as const,
    strokeLinejoin: "round" as const,
    "aria-hidden": true,
  };

  if (name === "chart") {
    return (
      <svg {...common}>
        <path d="M4 19V10" />
        <path d="M10 19V5" />
        <path d="M16 19v-7" />
        <path d="M22 19V3" />
      </svg>
    );
  }

  if (name === "calendar") {
    return (
      <svg {...common}>
        <rect x="3" y="4.5" width="18" height="16" rx="2" />
        <path d="M7 2.5v4M17 2.5v4M3 9h18" />
      </svg>
    );
  }

  if (name === "rank") {
    return (
      <svg {...common}>
        <path d="M12 4v16M8 20h8M7 8h10M9 4h6M5 8h14" />
        <path d="M8 8v4M16 8v4M5 12h3M16 12h3" />
      </svg>
    );
  }

  if (name === "wallet") {
    return (
      <svg {...common}>
        <path d="M3 7.5A2.5 2.5 0 0 1 5.5 5h14A1.5 1.5 0 0 1 21 6.5V18a2 2 0 0 1-2 2H5.5A2.5 2.5 0 0 1 3 17.5v-10Z" />
        <path d="M3 8h15.5A2.5 2.5 0 0 1 21 10.5V14h-5.5a2.5 2.5 0 0 1 0-5H21" />
        <circle cx="15.5" cy="11.5" r=".6" fill="currentColor" />
      </svg>
    );
  }

  if (name === "bank") {
    return (
      <svg {...common}>
        <path d="m3 9 9-5 9 5" />
        <path d="M5 10v7M9 10v7M15 10v7M19 10v7M3 19h18M2 21h20" />
      </svg>
    );
  }

  if (name === "refresh") {
    return (
      <svg {...common}>
        <path d="M20 11a8 8 0 0 0-14.7-4L3 10" />
        <path d="M3 5v5h5" />
        <path d="M4 13a8 8 0 0 0 14.7 4L21 14" />
        <path d="M21 19v-5h-5" />
      </svg>
    );
  }

  if (name === "bag") {
    return (
      <svg {...common}>
        <rect x="4" y="7" width="16" height="14" rx="2" />
        <path d="M8 7V5a4 4 0 0 1 8 0v2M8 12h8" />
      </svg>
    );
  }

  if (name === "info") {
    return (
      <svg {...common}>
        <circle cx="12" cy="12" r="9" />
        <path d="M12 11v5M12 8h.01" />
      </svg>
    );
  }

  if (name === "clock") {
    return (
      <svg {...common}>
        <circle cx="12" cy="12" r="9" />
        <path d="M12 7v5l3 2" />
      </svg>
    );
  }

  if (name === "arrow-up") {
    return (
      <svg {...common}>
        <path d="M12 19V5M7 10l5-5 5 5" />
      </svg>
    );
  }

  if (name === "arrow-down") {
    return (
      <svg {...common}>
        <path d="M12 5v14M7 14l5 5 5-5" />
      </svg>
    );
  }

  return (
    <svg {...common}>
      <path d="m9 6 6 6-6 6" />
    </svg>
  );
}

export default function AstrologerWalletPage() {
  const router = useRouter();

  const [summary, setSummary] = useState<AstrologerWalletSummary | null>(null);
  const [transactions, setTransactions] = useState<AstrologerWalletTransaction[]>([]);
  const [withdrawals, setWithdrawals] = useState<AstrologerWalletWithdrawHistory[]>([]);
  const [activeTab, setActiveTab] = useState<TransactionTab>("ALL");
  const [dateFilter, setDateFilter] = useState<DateFilter>("ALL");
  const [loadingSummary, setLoadingSummary] = useState(true);
  const [loadingTransactions, setLoadingTransactions] = useState(true);
  const [error, setError] = useState(false);
  const [astrologerToken, setAstrologerToken] = useState<string | null>(null);

  const loadSummary = useCallback(async (token: string) => {
    try {
      const response = await getAstrologerWallet(token);
      const data =
        response?.data?.data ??
        response?.data ??
        response;

      setSummary(data ?? null);
    } catch (err) {
      console.error("Wallet summary error:", err);
      setError(true);
      toast.error("Unable to load your wallet.");
    } finally {
      setLoadingSummary(false);
    }
  }, []);

  const loadTransactions = useCallback(async (token: string) => {
    setLoadingTransactions(true);
    setError(false);

    try {
      // The transactions endpoint is the source of earnings.
      // Withdrawals come from the dedicated withdraw-history endpoint.
      const results = await Promise.allSettled([
        getAstrologerWalletTransactions(token, 1, 10, "ALL"),
        getAstrologerWalletWithdrawHistory(token),
      ]);

      const transactionResult = results[0];
      const withdrawalResult = results[1];

      if (transactionResult.status === "fulfilled") {
        const transactionResponse = transactionResult.value;
        const transactionData =
          transactionResponse?.data?.data ??
          transactionResponse?.data ??
          transactionResponse;

        const transactionRows =
          transactionData?.transactions ??
          transactionData?.recordList ??
          transactionData?.records ??
          transactionData?.items ??
          [];

        setTransactions(Array.isArray(transactionRows) ? transactionRows : []);
      } else {
        console.error("Wallet transactions API error:", transactionResult.reason);
        setTransactions([]);
      }

      if (withdrawalResult.status === "fulfilled") {
        const withdrawalResponse = withdrawalResult.value;
        const withdrawalData =
          withdrawalResponse?.data?.data ??
          withdrawalResponse?.data ??
          withdrawalResponse;

        const withdrawalRows =
          Array.isArray(withdrawalData)
            ? withdrawalData
            : withdrawalData?.withdrawals ??
              withdrawalData?.recordList ??
              withdrawalData?.records ??
              withdrawalData?.items ??
              [];

        setWithdrawals(Array.isArray(withdrawalRows) ? withdrawalRows : []);
      } else {
        console.error("Wallet withdraw history API error:", withdrawalResult.reason);
        setWithdrawals([]);
      }

      if (transactionResult.status === "rejected" || withdrawalResult.status === "rejected") {
        setError(true);
        toast.error("Some wallet history could not be loaded.");
      }
    } catch (err) {
      console.error("Wallet transaction history error:", err);
      setTransactions([]);
      setWithdrawals([]);
      setError(true);
      toast.error("Unable to load transaction history.");
    } finally {
      setLoadingTransactions(false);
    }
  }, []);

  useEffect(() => {
    const token = localStorage.getItem("astrologerToken");

    if (!token) {
      router.replace("/astrologer/signin");
      return;
    }

    setAstrologerToken(token);
    void loadSummary(token);
    void loadTransactions(token);
  }, [loadSummary, loadTransactions, router]);


  const filteredTransactions = useMemo(() => {
    const combined: Array<AstrologerWalletTransaction | AstrologerWalletWithdrawHistory> = [
      ...transactions,
      ...withdrawals,
    ];

    return combined
      .filter((tx) => {
        const typeMatch =
          activeTab === "ALL" ||
          (activeTab === "WITHDRAWALS" && isWithdrawal(tx)) ||
          (activeTab === "EARNINGS" && isEarning(tx));

        return typeMatch && isInDateRange(getTransactionDate(tx), dateFilter);
      })
      .sort((a, b) => {
        const aDate = parseWalletDate(getTransactionDate(a))?.getTime() ?? 0;
        const bDate = parseWalletDate(getTransactionDate(b))?.getTime() ?? 0;
        return bDate - aDate;
      })
      .slice(0, 10);
  }, [transactions, withdrawals, activeTab, dateFilter]);

  const totalTransactions = filteredTransactions.length;


  return (
    <div className="astrologer-wallet-page">
      <DashboardSidebar active="Wallet" />

      <main className="astrologer-wallet-main">
        <div className="wallet-breadcrumb">
          <span>Home</span>
          <span className="wallet-breadcrumb-chevron">›</span>
          <strong>Wallet</strong>
        </div>

        <header className="wallet-page-header">
          <div>
            <h1>Wallet</h1>
            <p>Manage your earnings, withdrawals and transactions</p>
          </div>

          <NotificationBell
            audience="astrologer"
            token={astrologerToken}
            notificationsHref="/astrologer/notifications"
            dark
          />
        </header>

        <section className="wallet-stat-grid">
          <div className="wallet-stat-card">
            <div className="wallet-icon-box">
              <Icon name="chart" />
            </div>
            <div>
              <span>Last 3 Months<br />Earnings</span>
              <strong>
                {loadingSummary
                  ? "--"
                  : formatMoney(summary?.lastThreeMonthEarnings)}
              </strong>
            </div>
          </div>

          <div className="wallet-stat-card">
            <div className="wallet-icon-box">
              <Icon name="calendar" />
            </div>
            <div>
              <span>Monthly Earnings</span>
              <strong>
                {loadingSummary ? "--" : formatMoney(summary?.monthlyEarnings)}
              </strong>
            </div>
          </div>

          <div className="wallet-stat-card">
            <div className="wallet-icon-box">
              <Icon name="chart" />
            </div>
            <div>
              <span>Weekly Earnings</span>
              <strong>
                {loadingSummary ? "--" : formatMoney(summary?.weeklyEarnings)}
              </strong>
            </div>
          </div>

          <div className="wallet-stat-card">
            <div className="wallet-icon-box">
              <Icon name="rank" />
            </div>
            <div>
              <span>Rank</span>
              <strong>
                {loadingSummary
                  ? "--"
                  : Number(summary?.rank ?? 0).toLocaleString("en-IN")}
              </strong>
            </div>
          </div>
        </section>

        <div className="wallet-filter-row">
          <div className="wallet-date-control">
            <div className="wallet-select-wrap">
              <Icon name="calendar" size={18} />
              <select
                id="wallet-date"
                value={dateFilter}
                onChange={(e) => setDateFilter(e.target.value as DateFilter)}
              >
                <option value="TODAY">Today</option>
                <option value="WEEK">This Week</option>
                <option value="MONTH">This Month</option>
                <option value="ALL">All Time</option>
              </select>
            </div>
          </div>
        </div>

        <section className="wallet-top-grid">
          <div className="wallet-balance-card">
            <div className="wallet-balance-left">
              <div className="wallet-icon-box wallet-icon-box-large">
                <Icon name="wallet" size={28} />
              </div>
              <div>
                <div className="wallet-label-with-info">
                  <span>Available Balance</span>
                  <Icon name="info" size={16} />
                </div>
                <strong className="wallet-balance-value">
                  {loadingSummary ? "--" : formatMoney(summary?.availableBalance)}
                </strong>
              </div>
            </div>

            <Link
              href="/astrologer/wallet/withdraw"
              className="wallet-outline-button"
              aria-disabled={!summary?.availableBalance}
              onClick={(e) => {
                if (!summary?.availableBalance) {
                  e.preventDefault();
                }
              }}
            >
              <Icon name="bank" size={20} />
              Withdraw
            </Link>

            <div className="wallet-card-divider" />

            <div className="wallet-payable-row">
              <div>
                <div className="wallet-label-with-info">
                  <span>Payable Amount</span>
                  <Icon name="info" size={16} />
                </div>
                <strong className="wallet-payable-value">
                  {loadingSummary ? "--" : formatMoney(summary?.pendingEarnings)}
                </strong>
              </div>

              <Link
                href="/astrologer/wallet/settlement-history"
                className="wallet-yellow-outline-button"
                // aria-disabled={!summary?.payableAmount}
                // onClick={(e) => {
                //   if (!summary?.payableAmount) {
                //     e.preventDefault();
                //   }
                // }}
              >
                <Icon name="refresh" size={19} />
                Settlement
              </Link>

              {/* <button
                type="button"
                className="wallet-yellow-outline-button"
                disabled={!summary?.payableAmount}
                onClick={() =>
                  toast("Settlement flow is not connected to an API yet.")
                }
              >
                <Icon name="refresh" size={19} />
                Settlement
              </button> */}
            </div>
          </div>

        </section>

        <section className="wallet-transactions-card">
          <div className="wallet-transactions-header">
            <h2>Transaction History</h2>

            <div className="wallet-tabs">
              {(["ALL", "EARNINGS", "WITHDRAWALS"] as TransactionTab[]).map(
                (tab) => (
                  <button
                    key={tab}
                    type="button"
                    className={activeTab === tab ? "active" : ""}
                    onClick={() => setActiveTab(tab)}
                  >
                    {tab === "ALL"
                      ? "All"
                      : tab.charAt(0) + tab.slice(1).toLowerCase()}
                  </button>
                )
              )}
            </div>

            <button
              type="button"
              className="wallet-view-all"
              onClick={() => {
                setDateFilter("ALL");
                setActiveTab("ALL");
              }}
            >
              View All <Icon name="chevron" size={17} />
            </button>
          </div>

          <div className="wallet-table-wrap">
            <table className="wallet-table">
              <thead>
                <tr>
                  <th>Type</th>
                  <th>Description</th>
                  <th>Date &amp; Time</th>
                  <th>Status</th>
                  <th>Amount</th>
                </tr>
              </thead>

              <tbody>
                {loadingTransactions ? (
                  <tr>
                    <td colSpan={5} className="wallet-table-state">
                      Loading transactions...
                    </td>
                  </tr>
                ) : filteredTransactions.length === 0 ? (
                  <tr>
                    <td colSpan={5} className="wallet-table-state">
                      <div className="wallet-empty-icon">
                        <Icon name="wallet" size={24} />
                      </div>
                      <strong>No transactions found</strong>
                      <span>
                        {dateFilter === "TODAY"
                          ? "There are no wallet transactions for today."
                          : "Your wallet transactions will appear here."}
                      </span>
                    </td>
                  </tr>
                ) : (
                  filteredTransactions.map((tx, index) => {
                    const amount = getTransactionAmount(tx);
                    const withdrawal = isWithdrawal(tx);
                    const status = String(
                      tx.status ?? tx.transactionStatus ?? "Completed"
                    );
                    const detailHref = withdrawal
                      ? `/astrologer/wallet/transaction/${encodeURIComponent(String(tx.id ?? ""))}?type=withdrawal`
                      : `/astrologer/wallet/transaction/${encodeURIComponent(String(tx.id ?? ""))}?type=earning`;

                    return (
                      <tr
                        key={String(tx.id ?? tx.transactionId ?? index)}
                        className="wallet-table-row"
                        role="link"
                        tabIndex={0}
                        aria-label="View transaction details"
                        onClick={() => router.push(detailHref)}
                        onKeyDown={(event) => {
                          if (event.key === "Enter" || event.key === " ") {
                            event.preventDefault();
                            router.push(detailHref);
                          }
                        }}
                      >
                        <td>
                          <span
                            className={`wallet-type-icon ${
                              withdrawal ? "withdrawal" : "earning"
                            }`}
                          >
                            <Icon
                              name={withdrawal ? "arrow-down" : "arrow-up"}
                              size={19}
                            />
                          </span>
                        </td>
                        <td className="wallet-description">
                          {getTransactionDescription(tx)}
                        </td>
                        <td>{formatDateTime(getTransactionDate(tx))}</td>
                        <td>
                          <span
                            className={`wallet-status ${status
                              .toLowerCase()
                              .replace(/\s+/g, "-")}`}
                          >
                            {status}
                          </span>
                        </td>
                        <td
                          className={`wallet-amount ${
                            withdrawal ? "negative" : "positive"
                          }`}
                        >
                          {amount < 0 || withdrawal ? "-" : "+"}
                          {formatMoney(Math.abs(amount))}
                        </td>
                      </tr>
                    );
                  })
                )}
              </tbody>
            </table>
          </div>

          <div className="wallet-table-footer">
            <span>
              {error ? "Wallet data could not be loaded." : `${totalTransactions} transactions`}
            </span>
            <span>Showing up to 10 transactions</span>
          </div>
        </section>
      </main>

      <style jsx>{`
        .astrologer-wallet-page {
            min-height: 100vh;
            display: flex;
        }

        .astrologer-wallet-main {
          flex: 1;
          min-width: 0;
          padding: 28px 32px;
        }


        .wallet-breadcrumb {
          display: flex;
          align-items: center;
          gap: 9px;
          color: #aaa29c;
          font-size: 14px;
          margin-bottom: 8px;
        }

        .wallet-breadcrumb strong {
          color: #ddd6d0;
          font-weight: 500;
        }

        .wallet-breadcrumb-chevron {
          color: #736c67;
          font-size: 19px;
        }

        .wallet-page-header {
          display: flex;
          align-items: flex-start;
          justify-content: space-between;
          gap: 16px;
          flex-wrap: wrap;
        }

        .wallet-page-header h1 {
          margin: 0;
          font-size: 29px;
          line-height: 1.2;
          font-weight: 700;
          letter-spacing: -0.5px;
        }

        .wallet-page-header p {
          margin: 5px 0 17px;
          color: #b8b0aa;
          font-size: 15px;
        }

        .wallet-stat-grid {
          display: grid;
          grid-template-columns: repeat(4, minmax(0, 1fr));
          gap: 10px;
          margin-bottom: 25px;
        }

        .wallet-stat-card,
        .wallet-balance-card,
        .wallet-astromall-card,
        .wallet-transactions-card {
          border: 1px solid rgba(133, 112, 99, 0.32);
          background: linear-gradient(135deg, rgba(42, 33, 29, 0.95), rgba(29, 25, 23, 0.92));
          box-shadow: 0 12px 30px rgba(0, 0, 0, 0.2);
          border-radius: 13px;
        }

        .wallet-stat-card {
          min-height: 91px;
          padding: 17px 20px;
          display: flex;
          align-items: center;
          gap: 17px;
          box-sizing: border-box;
        }

        .wallet-icon-box {
          width: 48px;
          height: 48px;
          flex: 0 0 48px;
          border-radius: 10px;
          display: grid;
          place-items: center;
          color: #ffd900;
          background: rgba(106, 84, 0, 0.24);
          border: 1px solid rgba(255, 213, 0, 0.55);
        }

        .wallet-icon-box-large {
          width: 54px;
          height: 54px;
          flex-basis: 54px;
        }

        .wallet-stat-card span {
          display: block;
          color: #b8b0aa;
          font-size: 14px;
          line-height: 1.35;
          min-height: 19px;
        }

        .wallet-stat-card strong {
          display: block;
          margin-top: 4px;
          font-size: 23px;
          line-height: 1.1;
          color: #f6f1ed;
          font-weight: 700;
        }

        .wallet-filter-row {
          margin-bottom: 17px;
        }

        .wallet-date-control {
          display: flex;
          align-items: center;
          gap: 13px;
        }

        .wallet-date-control label {
          color: #ded8d3;
          font-size: 14px;
          font-weight: 500;
        }

        .wallet-select-wrap {
          width: 435px;
          height: 43px;
          display: flex;
          align-items: center;
          gap: 11px;
          padding: 0 13px;
          border-radius: 7px;
          border: 1px solid rgba(129, 109, 97, 0.4);
          background: rgba(35, 29, 26, 0.92);
          color: #c7c0ba;
          box-sizing: border-box;
        }

        .wallet-select-wrap select {
          width: 100%;
          border: 0;
          outline: 0;
          color: #eee8e3;
          background: transparent;
          font-size: 14px;
          appearance: auto;
        }
          .wallet-select-wrap select option {
          color: #eee8e3;
          background: rgba(35, 29, 26, 0.92);
        }

        .wallet-top-grid {
          display: grid;
          grid-template-columns: 1fr;
          gap: 14px;
          margin-bottom: 16px;
        }

        .wallet-balance-card {
          padding: 17px 24px;
          min-height: 170px;
          box-sizing: border-box;
          display: grid;
          grid-template-columns: 1fr auto;
          grid-template-rows: auto 1px auto;
          column-gap: 25px;
        }

        .wallet-balance-left {
          display: flex;
          align-items: center;
          gap: 18px;
        }

        .wallet-label-with-info {
          display: flex;
          align-items: center;
          gap: 7px;
          color: #c1b9b3;
          font-size: 14px;
        }

        .wallet-label-with-info svg {
          color: #aaa29c;
        }

        .wallet-balance-value {
          display: block;
          margin-top: 4px;
          color: #ffd800;
          font-size: 31px;
          line-height: 1;
        }

        :global(a.wallet-outline-button),
        :global(a.wallet-yellow-outline-button) {
          height: 38px;
          min-height: 38px;
          padding: 0 18px;
          border-radius: 7px;
          display: inline-flex;
          align-items: center;
          justify-content: center;
          gap: 8px;
          color: #eee8e2 !important;
          border: 1px solid rgba(151, 130, 116, 0.65);
          background: rgba(37, 30, 27, 0.75) !important;
          font-size: 14px;
          line-height: 1;
          font-weight: 600;
          text-decoration: none !important;
          white-space: nowrap;
          cursor: pointer;
          box-sizing: border-box;
        }

        :global(a.wallet-outline-button:hover),
        :global(a.wallet-outline-button:focus-visible),
        :global(a.wallet-yellow-outline-button:hover),
        :global(a.wallet-yellow-outline-button:focus-visible) {
          text-decoration: none !important;
        }

        :global(a.wallet-outline-button[aria-disabled="true"]),
        :global(a.wallet-yellow-outline-button[aria-disabled="true"]) {
          opacity: 0.5;
          cursor: not-allowed;
        }

        :global(a.wallet-yellow-outline-button) {
          color: #ffd900 !important;
          border-color: #d2ae00;
          background: rgba(37, 30, 27, 0.75) !important;
          min-width: 142px;
          height: 38px;
        }

        .wallet-card-divider {
          grid-column: 1 / -1;
          width: 100%;
          height: 1px;
          background: rgba(116, 98, 88, 0.28);
          margin: 11px 0 10px;
        }

        .wallet-payable-row {
          grid-column: 1 / -1;
          display: flex;
          align-items: center;
          justify-content: space-between;
        }

        .wallet-payable-value {
          display: block;
          margin-top: 4px;
          font-size: 22px;
          color: #f0ebe7;
        }

        .wallet-astromall-card {
          min-height: 170px;
          padding: 17px 23px;
          box-sizing: border-box;
        }

        .wallet-astromall-header {
          display: flex;
          align-items: center;
          gap: 14px;
          min-height: 48px;
        }

        .wallet-astromall-header strong {
          flex: 1;
          font-size: 16px;
        }

        .wallet-astromall-header > svg {
          color: #a9a19a;
        }

        .wallet-astromall-values {
          display: grid;
          grid-template-columns: 1fr 1px 1fr;
          align-items: center;
          min-height: 57px;
        }

        .wallet-astromall-values > div:not(.wallet-vertical-divider) {
          padding: 0 12px 0 0;
        }

        .wallet-astromall-values > div:last-child {
          padding-left: 19px;
        }

        .wallet-astromall-values span {
          display: flex;
          align-items: center;
          gap: 6px;
          color: #b9b0aa;
          font-size: 14px;
        }

        .wallet-astromall-values strong {
          display: block;
          margin-top: 5px;
          font-size: 21px;
        }

        .wallet-pending-label svg {
          color: #ffd800;
        }

        .wallet-vertical-divider {
          width: 1px;
          height: 43px;
          background: rgba(116, 98, 88, 0.5);
        }

        .wallet-transactions-card {
          overflow: hidden;
        }

        .wallet-transactions-header {
          min-height: 69px;
          padding: 0 18px;
          display: flex;
          align-items: center;
          gap: 16px;
          border-bottom: 1px solid rgba(116, 98, 88, 0.28);
        }

        .wallet-transactions-header h2 {
          margin: 0;
          flex: 1;
          font-size: 19px;
        }

        .wallet-tabs {
          display: flex;
          align-items: center;
          gap: 9px;
        }

        .wallet-tabs button {
          min-width: 99px;
          height: 36px;
          padding: 0 17px;
          border-radius: 6px;
          border: 1px solid rgba(141, 120, 106, 0.65);
          color: #eee8e2;
          background: rgba(41, 34, 31, 0.8);
          font-size: 14px;
          cursor: pointer;
        }

        .wallet-tabs button.active {
          color: #17130e;
          border-color: #ffd800;
          background: #ffd800;
          font-weight: 700;
        }

        .wallet-view-all {
          border: 0;
          background: transparent;
          color: #bdb5ae;
          display: inline-flex;
          align-items: center;
          gap: 4px;
          font-size: 14px;
          cursor: pointer;
        }

        .wallet-table-wrap {
          overflow-x: auto;
        }

        .wallet-table {
          width: 100%;
          border-collapse: collapse;
          min-width: 850px;
          font-size: 14px;
        }

        .wallet-table th,
        .wallet-table td {
          height: 49px;
          padding: 0 15px;
          text-align: left;
          border-bottom: 1px solid rgba(116, 98, 88, 0.2);
          white-space: nowrap;
        }

        .wallet-table th {
          height: 42px;
          color: #b8afa8;
          background: rgba(16, 14, 13, 0.35);
          font-size: 13px;
          font-weight: 500;
        }

        .wallet-table td {
          color: #ddd6d0;
        }

        .wallet-table tbody tr:last-child td {
          border-bottom: 0;
        }

        .wallet-description {
          color: #f2ede8 !important;
          font-weight: 500;
        }

        .wallet-type-icon {
          width: 32px;
          height: 32px;
          display: inline-grid;
          place-items: center;
          border-radius: 8px;
        }

        .wallet-type-icon.earning {
          color: #00dca6;
          border: 1px solid rgba(0, 220, 166, 0.45);
          background: rgba(0, 155, 115, 0.1);
        }

        .wallet-type-icon.withdrawal {
          color: #ff5862;
          border: 1px solid rgba(255, 76, 87, 0.5);
          background: rgba(160, 35, 45, 0.12);
        }

        .wallet-status {
          display: inline-flex;
          align-items: center;
          height: 30px;
          padding: 0 11px;
          border-radius: 6px;
          border: 1px solid rgba(0, 220, 166, 0.38);
          color: #00dca6;
          background: rgba(0, 151, 112, 0.1);
          font-size: 12px;
        }

        .wallet-status.processed,
        .wallet-status.pending {
          color: #ffd800;
          border-color: rgba(255, 216, 0, 0.4);
          background: rgba(150, 116, 0, 0.12);
        }

        .wallet-status.failed,
        .wallet-status.rejected,
        .wallet-status.cancelled {
          color: #ff5c65;
          border-color: rgba(255, 80, 90, 0.4);
          background: rgba(150, 30, 40, 0.12);
        }

        .wallet-amount {
          font-weight: 700;
          font-size: 15px;
        }

        .wallet-amount.positive {
          color: #00dca6;
        }

        .wallet-amount.negative {
          color: #ff4d57;
        }

        .wallet-table-row {
          cursor: pointer;
          transition: background 0.15s ease;
        }

        .wallet-table-row:hover,
        .wallet-table-row:focus-visible {
          background: rgba(255, 214, 0, 0.06);
        }

        .wallet-table-row:focus-visible {
          outline: 1px solid rgba(255, 214, 0, 0.5);
          outline-offset: -1px;
        }

        .wallet-table-state {
          height: 220px !important;
          text-align: center !important;
          color: #aaa19a !important;
        }

        .wallet-table-state > strong,
        .wallet-table-state > span {
          display: block;
          margin-top: 7px;
        }

        .wallet-empty-icon {
          width: 48px;
          height: 48px;
          margin: 0 auto 10px;
          border-radius: 50%;
          display: grid;
          place-items: center;
          color: #ffd800;
          border: 1px solid rgba(255, 216, 0, 0.35);
          background: rgba(106, 84, 0, 0.15);
        }

        .wallet-table-footer {
          min-height: 42px;
          padding: 0 17px;
          display: flex;
          align-items: center;
          justify-content: space-between;
          color: #8f8780;
          font-size: 12px;
          border-top: 1px solid rgba(116, 98, 88, 0.2);
        }

        @media (max-width: 1100px) {
          .astrologer-wallet-main {
            width: calc(100% - 180px);
            margin-left: 180px;
            padding: 16px 18px 28px;
          }

          .wallet-stat-grid {
            grid-template-columns: repeat(2, minmax(0, 1fr));
          }

          .wallet-top-grid {
            grid-template-columns: 1fr;
          }
        }

        @media (max-width: 760px) {
          .astrologer-wallet-main {
            width: 100%;
            margin-left: 0;
            padding: 16px 12px 24px;
          }

          .wallet-stat-grid {
            grid-template-columns: 1fr;
          }

          .wallet-date-control {
            align-items: flex-start;
            flex-direction: column;
            gap: 7px;
          }

          .wallet-select-wrap {
            width: 100%;
          }

          .wallet-balance-card {
            grid-template-columns: 1fr;
            gap: 13px;
          }

          .wallet-outline-button {
            width: 100%;
          }

          .wallet-payable-row {
            gap: 12px;
            align-items: flex-end;
          }

          .wallet-yellow-outline-button {
            min-width: 0;
          }

          .wallet-transactions-header {
            flex-wrap: wrap;
            padding: 14px;
          }

          .wallet-transactions-header h2 {
            flex-basis: 100%;
          }

          .wallet-view-all {
            margin-left: auto;
          }
        }
      `}</style>
    </div>
  );
}