import { createResource, createSignal, Show, For } from 'solid-js';
import {
  api,
  AdminLedgerEntry,
  AdminWallet,
  AdminReconcileRow,
  LedgerTypeFilter,
  getAdminCreditBalance,
  getAdminCreditLedger,
  adjustAdminCredits,
  reconcileAdminCredits,
  listAdminLedger,
} from '~/lib/api';

type ActiveTab = 'balance' | 'adjust' | 'reconcile' | 'platform';

const API = '';

function authHeaders(): Record<string, string> {
  const token =
    typeof sessionStorage !== 'undefined'
      ? sessionStorage.getItem('nxtgauge_admin_access_token') || ''
      : '';
  return {
    Accept: 'application/json',
    'Content-Type': 'application/json',
    ...(token ? { Authorization: `Bearer ${token}` } : {}),
  };
}

export default function CreditPage() {
  const [activeTab, setActiveTab] = createSignal<ActiveTab | 'ai_credits'>('balance');

  // AI Credits sub-tab state
  const [aiCreditsSubTab, setAiCreditsSubTab] = createSignal<'balance' | 'adjust' | 'reconcile'>('balance');
  const [aiUserId, setAiUserId] = createSignal('');
  const [aiSearchedUserId, setAiSearchedUserId] = createSignal('');
  const [aiBalance, setAiBalance] = createSignal<any>(null);
  const [aiLedger, setAiLedger] = createSignal<any[]>([]);
  const [aiSearchLoading, setAiSearchLoading] = createSignal(false);
  const [aiSearchError, setAiSearchError] = createSignal('');
  const [aiLedgerPage, setAiLedgerPage] = createSignal(1);
  const [aiLedgerLimit, setAiLedgerLimit] = createSignal(20);
  const [aiLedgerTotal, setAiLedgerTotal] = createSignal(0);
  
  // AI Adjust state
  const [aiAdjUserId, setAiAdjUserId] = createSignal('');
  const [aiAdjAmount, setAiAdjAmount] = createSignal(1);
  const [aiAdjType, setAiAdjType] = createSignal<'ADD' | 'DEDUCT'>('ADD');
  const [aiAdjReason, setAiAdjReason] = createSignal('');
  const [aiAdjIdempotencyKey, setAiAdjIdempotencyKey] = createSignal('');
  const [aiAdjLoading, setAiAdjLoading] = createSignal(false);
  const [aiAdjSuccess, setAiAdjSuccess] = createSignal('');
  const [aiAdjError, setAiAdjError] = createSignal('');

  // AI Reconcile state
  const [aiReconFrom, setAiReconFrom] = createSignal('');
  const [aiReconTo, setAiReconTo] = createSignal('');
  const [aiReconLoading, setAiReconLoading] = createSignal(false);
  const [aiReconResults, setAiReconResults] = createSignal<any>(null);
  const [aiReconError, setAiReconError] = createSignal('');

  // Balance & Ledger tab state
  const [userId, setUserId] = createSignal('');
  const [searchedUserId, setSearchedUserId] = createSignal('');
  const [wallet, setWallet] = createSignal<AdminWallet | null>(null);
  const [ledger, setLedger] = createSignal<AdminLedgerEntry[]>([]);
  const [balanceLoading, setBalanceLoading] = createSignal(false);
  const [balanceError, setBalanceError] = createSignal('');

  // Reward/Deduct tab state
  const [adjUserId, setAdjUserId] = createSignal('');
  const [adjAmount, setAdjAmount] = createSignal(1);
  const [adjType, setAdjType] = createSignal<'ADD' | 'DEDUCT'>('ADD');
  const [adjReason, setAdjReason] = createSignal('');
  const [adjLoading, setAdjLoading] = createSignal(false);
  const [adjSuccess, setAdjSuccess] = createSignal('');
  const [adjError, setAdjError] = createSignal('');
  const [adjLastResult, setAdjLastResult] = createSignal<any>(null);

  // Reconcile tab state
  const [reconFrom, setReconFrom] = createSignal(defaultFromDate());
  const [reconTo, setReconTo] = createSignal(defaultToDate());
  const [reconLoading, setReconLoading] = createSignal(false);
  const [reconResults, setReconResults] = createSignal<AdminReconcileRow[]>([]);
  const [reconError, setReconError] = createSignal('');

  // Platform ledger tab state
  const [platformLedger, { refetch: refetchPlatform }] = createResource<AdminLedgerEntry[]>(
    () => listAdminLedger().then((r) => r.data?.entries ?? []),
  );

  const handleSearch = async () => {
    const uid = userId().trim();
    if (!uid) return;
    setBalanceLoading(true);
    setBalanceError('');
    setWallet(null);
    setLedger([]);
    setSearchedUserId(uid);
    try {
      const [balRes, ledRes] = await Promise.all([
        getAdminCreditBalance(uid),
        getAdminCreditLedger(uid, { limit: 100 }),
      ]);
      setWallet(balRes.data);
      setLedger(ledRes.data.entries ?? []);
    } catch (e: any) {
      setBalanceError(e?.message || 'Failed to fetch TraceCoin data for this user ID.');
    } finally {
      setBalanceLoading(false);
    }
  };

  const handleAdjust = async (e: Event) => {
    e.preventDefault();
    const uid = adjUserId().trim();
    const reason = adjReason().trim();
    if (!uid) {
      setAdjError('User ID is required.');
      return;
    }
    if (!reason) {
      setAdjError('Reason is required.');
      return;
    }
    if (!Number.isFinite(adjAmount()) || adjAmount() <= 0) {
      setAdjError('Amount must be a positive number.');
      return;
    }
    setAdjLoading(true);
    setAdjSuccess('');
    setAdjError('');
    setAdjLastResult(null);
    try {
      const res = await adjustAdminCredits({
        user_id: uid,
        amount: adjAmount(),
        type: adjType(),
        reason,
      });
      setAdjSuccess(
        `${adjType() === 'ADD' ? 'Added' : 'Deducted'} ${adjAmount()} tracecoins. New balance: ${res.data.balance}.`,
      );
      setAdjLastResult(res.data);
      setAdjUserId('');
      setAdjAmount(1);
      setAdjType('ADD');
      setAdjReason('');
    } catch (err: any) {
      setAdjError(err?.message || 'Failed to adjust credits');
    } finally {
      setAdjLoading(false);
    }
  };

  const handleReconcile = async (e: Event) => {
    e.preventDefault();
    setReconLoading(true);
    setReconError('');
    setReconResults([]);
    try {
      const res = await reconcileAdminCredits({
        from: new Date(reconFrom()).toISOString(),
        to: new Date(reconTo()).toISOString(),
      });
      setReconResults(res.data.results ?? []);
    } catch (err: any) {
      setReconError(err?.message || 'Failed to reconcile');
    } finally {
      setReconLoading(false);
    }
  };

  const tabs: { key: ActiveTab | 'ai_credits'; label: string }[] = [
    { key: 'balance', label: 'Balance & Ledger' },
    { key: 'adjust', label: 'Reward / Deduct' },
    { key: 'reconcile', label: 'Reconcile' },
    { key: 'platform', label: 'Platform Ledger' },
    { key: 'ai_credits', label: 'AI Credits' },
  ];

  // AI Credits handlers
  const handleAiSearch = async () => {
    const uid = aiUserId().trim();
    if (!uid) return;
    setAiSearchLoading(true);
    setAiSearchError('');
    setAiBalance(null);
    setAiLedger([]);
    setAiSearchedUserId(uid);
    try {
      const [balRes, ledRes] = await Promise.all([
        fetch(`${API}/api/admin/ai-credits/balance?userId=${encodeURIComponent(uid)}`, { headers: authHeaders(), credentials: 'include' }),
        fetch(`${API}/api/admin/ai-credits/ledger?userId=${encodeURIComponent(uid)}&page=${aiLedgerPage()}&limit=${aiLedgerLimit()}`, { headers: authHeaders(), credentials: 'include' }),
      ]);
      if (!balRes.ok || !ledRes.ok) throw new Error('Failed to fetch');
      const balData = await balRes.json();
      const ledData = await ledRes.json();
      setAiBalance(balData);
      setAiLedger(ledData.data ?? []);
      setAiLedgerTotal(ledData.total ?? 0);
    } catch {
      setAiSearchError('Failed to fetch AI credits data for this user ID.');
      setAiBalance(null);
      setAiLedger([]);
    } finally {
      setAiSearchLoading(false);
    }
  };

  const handleAiAdjust = async (e: Event) => {
    e.preventDefault();
    setAiAdjLoading(true);
    setAiAdjSuccess('');
    setAiAdjError('');
    try {
      // Generate idempotency key if not provided
      const idempotencyKey = aiAdjIdempotencyKey().trim() || crypto.randomUUID();
      const res = await fetch(`${API}/api/admin/ai-credits/adjust`, {
        method: 'POST',
        headers: authHeaders(),
        credentials: 'include',
        body: JSON.stringify({
          user_id: aiAdjUserId(),
          amount: aiAdjAmount(),
          type: aiAdjType(),
          reason: aiAdjReason(),
          idempotency_key: idempotencyKey,
        }),
      });
      if (!res.ok) {
        const d = await res.json().catch(() => ({}));
        throw new Error((d as any).error || 'Failed to adjust credits');
      }
      setAiAdjSuccess('AI credits adjusted successfully!');
      setAiAdjUserId('');
      setAiAdjAmount(1);
      setAiAdjType('ADD');
      setAiAdjReason('');
      setAiAdjIdempotencyKey('');
    } catch (err: any) {
      setAiAdjError(err.message || 'Failed to adjust credits');
    } finally {
      setAiAdjLoading(false);
    }
  };

  const handleAiReconcile = async (e: Event) => {
    e.preventDefault();
    setAiReconLoading(true);
    setAiReconError('');
    setAiReconResults(null);
    try {
      const fromDate = new Date(aiReconFrom()).toISOString();
      const toDate = new Date(aiReconTo()).toISOString();
      const res = await fetch(
        `${API}/api/admin/ai-credits/reconcile?from=${encodeURIComponent(fromDate)}&to=${encodeURIComponent(toDate)}`,
        { headers: authHeaders(), credentials: 'include' }
      );
      if (!res.ok) throw new Error('Failed to reconcile');
      const data = await res.json();
      setAiReconResults(data);
    } catch (err: any) {
      setAiReconError(err.message || 'Failed to reconcile');
    } finally {
      setAiReconLoading(false);
    }
  };

  const exportLedgerCsv = (entries: AdminLedgerEntry[], filename: string) => {
    const headers = ['Type', 'Amount', 'Balance After', 'Reason', 'Reference', 'Date'];
    const rows = entries.map((entry) => [
      entry.entry_type,
      `${entry.amount > 0 ? '+' : ''}${entry.amount ?? 0}`,
      entry.balance_after ?? '—',
      entry.reason || '—',
      entry.reference_id || '—',
      entry.created_at ? new Date(entry.created_at).toLocaleString('en-IN') : '—',
    ]);
    const csv = [headers, ...rows]
      .map((line) => line.map((cell) => `"${String(cell).replace(/"/g, '""')}"`).join(','))
      .join('\n');
    const blob = new Blob([csv], { type: 'text/csv;charset=utf-8;' });
    const url = URL.createObjectURL(blob);
    const link = document.createElement('a');
    link.href = url;
    link.download = filename;
    link.click();
    URL.revokeObjectURL(url);
  };

  return (
    <div class="w-full space-y-6 pb-8">
      <div style="margin-bottom:1.5rem">
        <h1 class="text-[28px] font-bold leading-tight text-[#111827]">Credit Management</h1>
        <p class="mt-1 text-[14px] text-[#6B7280]">Audit TraceCoin balances and adjust credits</p>
      </div>

      {/* Tabs */}
      <div class="bg-white border-b border-gray-200 px-6 flex items-center gap-8 sticky top-0 z-10">
        <For each={tabs}>
          {(tab) => (
            <button
              type="button"
              class={
                activeTab() === tab.key
                  ? 'py-3 border-b-2 border-orange-500 text-orange-600 text-sm font-medium'
                  : 'py-3 border-b-2 border-transparent text-gray-500 hover:text-gray-700 text-sm font-medium transition-colors'
              }
              onClick={() => setActiveTab(tab.key)}
            >
              {tab.label}
            </button>
          )}
        </For>
      </div>

      {/* Balance & Ledger Tab */}
      <Show when={activeTab() === 'balance'}>
        <section class="rounded-xl border border-gray-200 bg-white shadow-sm" style="margin-top:1.5rem">
          <div style="padding:20px">
            <h2 class="text-base font-bold text-slate-900 mb-2">Search Account Balance</h2>
            <div style="display:flex;gap:10px">
              <input
                type="text"
                placeholder="Enter User ID (UUID)..."
                value={userId()}
                onInput={(e) => setUserId(e.currentTarget.value)}
                onKeyDown={(e) => e.key === 'Enter' && handleSearch()}
                class="rounded-lg border border-gray-200 px-3 py-2 text-sm"
                style="flex:1"
              />
              <button class="btn-primary" onClick={handleSearch} disabled={balanceLoading()}>
                {balanceLoading() ? 'Searching...' : 'Search'}
              </button>
            </div>
            <Show when={balanceError()}>
              <div class="mt-3 rounded-lg border border-red-200 bg-red-50 px-4 py-3 text-sm text-red-700">
                {balanceError()}
              </div>
            </Show>
          </div>

          <Show when={wallet()}>
            {(w) => (
              <div style="padding:0 20px 20px">
                <div style="display:flex;justify-content:flex-end;margin-bottom:12px">
                  <button
                    type="button"
                    class="btn-primary"
                    style="padding:6px 12px;font-size:12px"
                    onClick={() => {
                      setAdjUserId(searchedUserId());
                      setActiveTab('adjust');
                    }}
                  >
                    Adjust this wallet
                  </button>
                </div>
                <div style="display:grid;grid-template-columns:repeat(4, 1fr);gap:12px;margin-bottom:20px">
                  <div class="rounded-xl p-4" style="background:#2563eb;color:#fff">
                    <p style="font-size:11px;font-weight:700;text-transform:uppercase;letter-spacing:.05em;color:#bfdbfe;margin:0 0 8px">
                      Balance
                    </p>
                    <p style="font-size:32px;font-weight:900;margin:0;line-height:1">{w().balance}</p>
                    <p style="font-size:11px;color:#bfdbfe;margin:6px 0 0">TraceCoins</p>
                  </div>
                  <div class="rounded-xl p-4" style="background:#7c3aed;color:#fff">
                    <p style="font-size:11px;font-weight:700;text-transform:uppercase;letter-spacing:.05em;color:#ddd6fe;margin:0 0 8px">
                      Reserved
                    </p>
                    <p style="font-size:32px;font-weight:900;margin:0;line-height:1">{w().reserved}</p>
                    <p style="font-size:11px;color:#ddd6fe;margin:6px 0 0">Pending requests</p>
                  </div>
                  <div class="rounded-xl p-4" style="background:#16a34a;color:#fff">
                    <p style="font-size:11px;font-weight:700;text-transform:uppercase;letter-spacing:.05em;color:#bbf7d0;margin:0 0 8px">
                      Available
                    </p>
                    <p style="font-size:32px;font-weight:900;margin:0;line-height:1">{w().available}</p>
                    <p style="font-size:11px;color:#bbf7d0;margin:6px 0 0">Ready to spend</p>
                  </div>
                  <div class="rounded-xl p-4 border border-gray-200" style="background:#fff">
                    <p style="font-size:11px;font-weight:700;text-transform:uppercase;letter-spacing:.05em;color:#64748b;margin:0 0 8px">
                      User
                    </p>
                    <p style="font-size:12px;font-weight:600;color:#0f172a;margin:0;word-break:break-all">
                      {searchedUserId()}
                    </p>
                    <p style="font-size:11px;color:#94a3b8;margin:6px 0 0">
                      Updated {new Date(w().updated_at).toLocaleString('en-IN')}
                    </p>
                  </div>
                </div>

                <LedgerSection
                  entries={ledger()}
                  onExport={() => exportLedgerCsv(ledger(), `ledger-${searchedUserId()}.csv`)}
                />
              </div>
            )}
          </Show>

          <Show when={!wallet() && !balanceLoading() && !balanceError()}>
            <p style="padding:24px 20px 32px;text-align:center;color:#94a3b8;font-style:italic">
              Enter a user ID to view their balance and ledger.
            </p>
          </Show>
        </section>
      </Show>

      {/* Reward / Deduct Tab */}
      <Show when={activeTab() === 'adjust'}>
        <section class="rounded-xl border border-gray-200 bg-white shadow-sm" style="max-width:560px;margin-top:1.5rem">
          <div style="padding:24px">
            <h2 style="margin:0 0 6px;font-size:16px;font-weight:700;color:#1e293b">
              Reward or Adjust TraceCoins
            </h2>
            <p style="margin:0 0 20px;font-size:13px;color:#64748b">
              Use this to reward TraceCoins for a valid support case, process a refund, or correct a balance manually.
              Every adjustment is written to the immutable ledger and the audit log.
            </p>
            <Show when={adjSuccess()}>
              <div class="mb-4 rounded-lg border border-green-200 bg-green-50 px-4 py-3 text-sm text-green-700">
                {adjSuccess()}
              </div>
            </Show>
            <Show when={adjError()}>
              <div class="mb-4 rounded-lg border border-red-200 bg-red-50 px-4 py-3 text-sm text-red-700">
                {adjError()}
              </div>
            </Show>
            <Show when={adjLastResult()}>
              <div class="mb-4 rounded-lg border border-blue-200 bg-blue-50 p-3 text-xs text-blue-900">
                <div><strong>Ledger entry:</strong> {adjLastResult().ledger_entry_id}</div>
                <div><strong>Balance:</strong> {adjLastResult().balance} | <strong>Reserved:</strong> {adjLastResult().reserved}</div>
                <div><strong>Reason:</strong> {adjLastResult().reason}</div>
                <div><strong>Audit logged:</strong> {String(adjLastResult().audit_logged)} | <strong>User notified:</strong> {String(adjLastResult().user_notified)}</div>
              </div>
            </Show>
            <form onSubmit={handleAdjust} style="display:flex;flex-direction:column;gap:14px">
              <div>
                <label style="display:block;font-size:13px;font-weight:600;margin-bottom:4px">
                  User ID *
                </label>
                <input
                  type="text"
                  required
                  placeholder="UUID"
                  value={adjUserId()}
                  onInput={(e) => setAdjUserId(e.currentTarget.value)}
                  style="width:100%;padding:8px 10px;border:1px solid #e2e8f0;border-radius:6px;font-size:14px;box-sizing:border-box"
                />
              </div>
              <div style="display:grid;grid-template-columns:1fr 1fr;gap:12px">
                <div>
                  <label style="display:block;font-size:13px;font-weight:600;margin-bottom:4px">
                    Amount *
                  </label>
                  <input
                    type="number"
                    min="1"
                    required
                    value={adjAmount()}
                    onInput={(e) => setAdjAmount(Number(e.currentTarget.value))}
                    style="width:100%;padding:8px 10px;border:1px solid #e2e8f0;border-radius:6px;font-size:14px;box-sizing:border-box"
                  />
                </div>
                <div>
                  <label style="display:block;font-size:13px;font-weight:600;margin-bottom:4px">
                    Type *
                  </label>
                  <select
                    value={adjType()}
                    onChange={(e) => setAdjType(e.currentTarget.value as 'ADD' | 'DEDUCT')}
                    style="width:100%;padding:8px 10px;border:1px solid #e2e8f0;border-radius:6px;font-size:14px;box-sizing:border-box"
                  >
                    <option value="ADD">ADD (credit)</option>
                    <option value="DEDUCT">DEDUCT (debit)</option>
                  </select>
                </div>
              </div>
              <div>
                <label style="display:block;font-size:13px;font-weight:600;margin-bottom:4px">
                  Reason * <span style="font-weight:400;color:#94a3b8">(recorded in audit log)</span>
                </label>
                <input
                  type="text"
                  required
                  value={adjReason()}
                  onInput={(e) => setAdjReason(e.currentTarget.value)}
                  placeholder="e.g. Support case #1234 refund"
                  style="width:100%;padding:8px 10px;border:1px solid #e2e8f0;border-radius:6px;font-size:14px;box-sizing:border-box"
                />
              </div>
              <div>
                <button class="btn-primary" type="submit" disabled={adjLoading()}>
                  {adjLoading() ? 'Adjusting...' : `${adjType() === 'ADD' ? 'Add' : 'Deduct'} TraceCoins`}
                </button>
              </div>
            </form>
          </div>
        </section>
      </Show>

      {/* Reconcile Tab */}
      <Show when={activeTab() === 'reconcile'}>
        <section class="rounded-xl border border-gray-200 bg-white shadow-sm" style="margin-top:1.5rem">
          <div style="padding:24px">
            <h2 style="margin:0 0 6px;font-size:16px;font-weight:700;color:#1e293b">
              Reconcile wallets
            </h2>
            <p style="margin:0 0 16px;font-size:13px;color:#64748b">
              Compare the sum of ledger entries (over the chosen window) against each wallet's actual `balance`.
              Anything not equal to zero is a discrepancy worth investigating.
            </p>
            <form
              onSubmit={handleReconcile}
              style="display:grid;grid-template-columns:1fr 1fr auto;gap:12px;align-items:flex-end"
            >
              <div>
                <label style="display:block;font-size:12px;font-weight:600;margin-bottom:4px">From</label>
                <input
                  type="datetime-local"
                  value={reconFrom()}
                  onInput={(e) => setReconFrom(e.currentTarget.value)}
                  style="width:100%;padding:8px 10px;border:1px solid #e2e8f0;border-radius:6px;font-size:13px"
                />
              </div>
              <div>
                <label style="display:block;font-size:12px;font-weight:600;margin-bottom:4px">To</label>
                <input
                  type="datetime-local"
                  value={reconTo()}
                  onInput={(e) => setReconTo(e.currentTarget.value)}
                  style="width:100%;padding:8px 10px;border:1px solid #e2e8f0;border-radius:6px;font-size:13px"
                />
              </div>
              <button class="btn-primary" type="submit" disabled={reconLoading()}>
                {reconLoading() ? 'Reconciling...' : 'Reconcile'}
              </button>
            </form>
            <Show when={reconError()}>
              <div class="mt-4 rounded-lg border border-red-200 bg-red-50 px-4 py-3 text-sm text-red-700">
                {reconError()}
              </div>
            </Show>
            <Show when={reconResults().length > 0}>
              <div class="overflow-x-auto" style="margin-top:16px">
                <table class="data-table w-full text-sm">
                  <thead>
                    <tr>
                      <th>User ID</th>
                      <th>Email</th>
                      <th class="text-right">Expected (ledger)</th>
                      <th class="text-right">Actual (wallet)</th>
                      <th class="text-right">Discrepancy</th>
                    </tr>
                  </thead>
                  <tbody>
                    <For each={reconResults()}>
                      {(row) => (
                        <tr>
                          <td class="font-mono text-xs">{row.user_id}</td>
                          <td class="text-slate-500">{row.user_email ?? '—'}</td>
                          <td class="text-right">{row.expected_balance}</td>
                          <td class="text-right">{row.actual_balance}</td>
                          <td
                            class="text-right font-semibold"
                            style={row.discrepancy === 0 ? 'color:#16a34a' : 'color:#dc2626'}
                          >
                            {row.discrepancy}
                          </td>
                        </tr>
                      )}
                    </For>
                  </tbody>
                </table>
              </div>
            </Show>
            <Show when={!reconLoading() && reconResults().length === 0 && !reconError()}>
              <p class="mt-4 text-center text-sm text-slate-500 italic">
                Run a reconciliation to see results.
              </p>
            </Show>
          </div>
        </section>
      </Show>

      {/* Platform Ledger Tab */}
      <Show when={activeTab() === 'platform'}>
        <section class="rounded-xl border border-gray-200 bg-white shadow-sm" style="margin-top:1.5rem">
          <div style="padding:14px 20px;border-bottom:1px solid #F3F4F6;display:flex;justify-content:flex-end;gap:8px">
            <button class="btn-secondary" onClick={() => void refetchPlatform()}>
              Refresh
            </button>
            <button
              class="btn-primary"
              style="height:34px;padding:0 12px;font-size:12px"
              onClick={() =>
                exportLedgerCsv(platformLedger() ?? [], 'platform-ledger.csv')
              }
            >
              Export CSV
            </button>
          </div>
          <Show
            when={!platformLedger.loading}
            fallback={<p style="padding:32px;text-align:center;color:#64748b">Loading ledger...</p>}
          >
            <LedgerSection entries={platformLedger() ?? []} showUser onExport={undefined} />
          </Show>
        </section>
      </Show>

      {/* AI Credits Tab */}
      <Show when={activeTab() === 'ai_credits'}>
        <section class="rounded-xl border border-gray-200 bg-white shadow-sm" style="margin-top:1.5rem">
          <div>
              {/* AI Credits Sub-tabs */}
              <div class="bg-white border-b border-gray-200 px-0 flex items-center gap-6 mb-6">
                <For each={['balance', 'adjust', 'reconcile'] as const}>{(t) => (
                  <button
                    type="button"
                    class={
                      aiCreditsSubTab() === t
                        ? "py-2 border-b-2 border-orange-500 text-orange-600 text-sm font-medium"
                        : "py-2 border-b-2 border-transparent text-gray-500 hover:text-gray-700 text-sm font-medium transition-colors"
                    }
                    onClick={() => setAiCreditsSubTab(t)}
                  >
                    {t === 'balance' ? 'Balance & Ledger' : t === 'adjust' ? 'Reward / Deduct' : 'Reconcile'}
                  </button>
                )}</For>
              </div>

              {/* AI Balance & Ledger */}
              <Show when={aiCreditsSubTab() === 'balance'}>
                <div style="display:flex;flex-direction:column;gap:24px">
                  <section class="rounded-xl border border-gray-200 bg-white shadow-sm p-6">
                    <h2 style="margin:0 0 16px;font-size:16px;font-weight:700;color:#1e293b">Search AI Credits Balance</h2>
                    <div style="display:flex;gap:10px">
                      <input
                        type="text"
                        placeholder="Enter User ID..."
                        value={aiUserId()}
                        onInput={(e) => setAiUserId(e.currentTarget.value)}
                        onKeyDown={(e) => e.key === 'Enter' && handleAiSearch()}
                        class="rounded-lg border border-gray-200 px-3 py-2 text-sm"
                        style="flex:1"
                      />
                      <button
                        class="btn-primary"
                        onClick={handleAiSearch}
                        disabled={aiSearchLoading()}
                      >
                        {aiSearchLoading() ? 'Searching...' : 'Search'}
                      </button>
                    </div>
                    <Show when={aiSearchError()}>
                      <div class="mb-4 rounded-lg border border-red-200 bg-red-50 px-4 py-3 text-sm text-red-700" style="margin-top:10px">{aiSearchError()}</div>
                    </Show>
                  </section>

                  <Show when={aiBalance() !== null}>
                    <div style="display:grid;grid-template-columns:1fr 2fr;gap:20px">
                      <div style="background:#7c3aed;border-radius:12px;padding:24px;color:#fff">
                        <p style="font-size:11px;font-weight:700;text-transform:uppercase;letter-spacing:0.05em;color:#ddd6fe;margin:0 0 8px">Available AI Credits</p>
                        <p style="font-size:36px;font-weight:900;margin:0">{aiBalance().available_credits ?? 0}</p>
                        <p style="font-size:12px;color:#ddd6fe;margin:8px 0 0">User: {aiSearchedUserId()}</p>
                        <div style="margin-top:16px;border-top:1px solid rgba(255,255,255,0.2);padding-top:12px">
                          <p style="font-size:11px;color:#ddd6fe;margin:0 0 4px">Monthly: {aiBalance().monthly_credits_used ?? 0} / {aiBalance().monthly_credits_total ?? 0}</p>
                          <p style="font-size:11px;color:#ddd6fe;margin:0 0 4px">Purchased: {aiBalance().purchased_credits_used ?? 0} / {aiBalance().purchased_credits_total ?? 0}</p>
                          <p style="font-size:11px;color:#ddd6fe;margin:0">Bonus: {aiBalance().bonus_credits_used ?? 0} / {aiBalance().bonus_credits_total ?? 0}</p>
                        </div>
                      </div>

                      <div class="table-card" style="overflow:hidden">
                        <h3 style="margin:0 0 16px;font-size:15px;font-weight:700;color:#0f172a">AI Credits Ledger</h3>
                        <Show when={aiLedger().length === 0}>
                          <p style="text-align:center;padding:32px;color:#94a3b8;font-style:italic">No transactions found for this account.</p>
                        </Show>
                        <Show when={aiLedger().length > 0}>
                          <div class="overflow-x-auto">
                            <table class="data-table w-full text-sm">
                              <thead>
                                <tr>
                                  <th>Type</th>
                                  <th>Credits</th>
                                  <th>Balance After</th>
                                  <th>Description</th>
                                  <th>Date</th>
                                </tr>
                              </thead>
                              <tbody>
                                <For each={aiLedger()}>
                                  {(entry) => (
                                    <tr class="hover:bg-slate-50">
                                      <td>
                                        <span
                                          style={`display:inline-block;padding:2px 8px;border-radius:999px;font-size:10px;font-weight:700;text-transform:uppercase;background:${entry.credits > 0 ? '#dcfce7' : '#fee2e2'};color:${entry.credits > 0 ? '#15803d' : '#b91c1c'}`}
                                        >
                                          {entry.credits > 0 ? 'CREDIT' : 'DEBIT'}
                                        </span>
                                      </td>
                                      <td class="font-semibold text-slate-900" style={entry.credits > 0 ? 'color:#16a34a' : 'color:#dc2626'}>
                                        {entry.credits > 0 ? '+' : ''}{entry.credits}
                                      </td>
                                      <td class="text-slate-700">{entry.balance_after}</td>
                                      <td class="text-slate-500" style="font-size:12px">{entry.description || '—'}</td>
                                      <td class="text-slate-500" style="font-size:12px">
                                        {entry.created_at ? new Date(entry.created_at).toLocaleString() : '—'}
                                      </td>
                                    </tr>
                                  )}
                                </For>
                              </tbody>
                            </table>
                          </div>
                          <div style="padding:10px 16px;font-size:12px;color:#64748b;border-top:1px solid #f1f5f9">
                            Showing {aiLedger().length} of {aiLedgerTotal()} entries (Page {aiLedgerPage()})
                          </div>
                        </Show>
                      </div>
                    </div>
                  </Show>
                </div>
              </Show>

              {/* AI Reward / Deduct */}
              <Show when={aiCreditsSubTab() === 'adjust'}>
                <section class="rounded-xl border border-gray-200 bg-white shadow-sm" style="max-width:460px">
                  <h2 style="margin:0 0 6px;font-size:16px;font-weight:700;color:#1e293b">Reward or Adjust AI Credits</h2>
                  <p style="margin:0 0 20px;font-size:13px;color:#64748b">
                    Use this to reward AI credits for a valid support case, process a refund, or correct a balance manually.
                  </p>
                  <Show when={aiAdjSuccess()}>
                    <div style="background:#dcfce7;border:1px solid #86efac;border-radius:6px;padding:10px 14px;margin-bottom:14px;font-size:14px;color:#15803d;font-weight:600">
                      {aiAdjSuccess()}
                    </div>
                  </Show>
                  <Show when={aiAdjError()}>
                    <div class="mb-4 rounded-lg border border-red-200 bg-red-50 px-4 py-3 text-sm text-red-700" style="margin-bottom:14px">{aiAdjError()}</div>
                  </Show>
                  <form onSubmit={handleAiAdjust} style="display:flex;flex-direction:column;gap:14px">
                    <div class="field">
                      <label style="display:block;font-size:13px;font-weight:600;margin-bottom:4px">User ID</label>
                      <input
                        type="text"
                        required
                        value={aiAdjUserId()}
                        onInput={(e) => setAiAdjUserId(e.currentTarget.value)}
                        style="width:100%;padding:8px 10px;border:1px solid #e2e8f0;border-radius:6px;font-size:14px;box-sizing:border-box"
                      />
                    </div>
                    <div class="mt-4 grid grid-cols-1 gap-4 sm:grid-cols-2">
                      <div class="field">
                        <label style="display:block;font-size:13px;font-weight:600;margin-bottom:4px">Amount</label>
                        <input
                          type="number"
                          min="1"
                          required
                          value={aiAdjAmount()}
                          onInput={(e) => setAiAdjAmount(Number(e.currentTarget.value))}
                          style="width:100%;padding:8px 10px;border:1px solid #e2e8f0;border-radius:6px;font-size:14px;box-sizing:border-box"
                        />
                      </div>
                      <div class="field">
                        <label style="display:block;font-size:13px;font-weight:600;margin-bottom:4px">Type</label>
                        <select
                          value={aiAdjType()}
                          onChange={(e) => setAiAdjType(e.currentTarget.value as 'ADD' | 'DEDUCT')}
                          style="width:100%;padding:8px 10px;border:1px solid #e2e8f0;border-radius:6px;font-size:14px;box-sizing:border-box"
                        >
                          <option value="ADD">ADD</option>
                          <option value="DEDUCT">DEDUCT</option>
                        </select>
                      </div>
                    </div>
                    <div class="field">
                      <label style="display:block;font-size:13px;font-weight:600;margin-bottom:4px">Reason <span style="color:#dc2626">*</span></label>
                      <input
                        type="text"
                        required
                        value={aiAdjReason()}
                        onInput={(e) => setAiAdjReason(e.currentTarget.value)}
                        placeholder="Required: Explain why credits are being adjusted"
                        style="width:100%;padding:8px 10px;border:1px solid #e2e8f0;border-radius:6px;font-size:14px;box-sizing:border-box"
                      />
                    </div>
                    <div class="field">
                      <label style="display:block;font-size:13px;font-weight:600;margin-bottom:4px">Idempotency Key <span style="font-weight:400;color:#94a3b8">(optional)</span></label>
                      <input
                        type="text"
                        value={aiAdjIdempotencyKey()}
                        onInput={(e) => setAiAdjIdempotencyKey(e.currentTarget.value)}
                        placeholder="Leave empty to auto-generate"
                        style="width:100%;padding:8px 10px;border:1px solid #e2e8f0;border-radius:6px;font-size:14px;box-sizing:border-box"
                      />
                      <p style="font-size:11px;color:#64748b;margin-top:4px">Prevents duplicate adjustments if resubmitted</p>
                    </div>
                    <div>
                      <button class="btn-primary" type="submit" disabled={aiAdjLoading()}>
                        {aiAdjLoading() ? 'Adjusting...' : 'Apply Adjustment'}
                      </button>
                    </div>
                  </form>
                </section>
              </Show>

              {/* AI Reconcile */}
              <Show when={aiCreditsSubTab() === 'reconcile'}>
                <div style="display:flex;flex-direction:column;gap:20px">
                  <section class="rounded-xl border border-gray-200 bg-white shadow-sm" style="max-width:460px">
                    <h2 style="margin:0 0 16px;font-size:16px;font-weight:700;color:#1e293b">AI Credits Reconciliation</h2>
                    <Show when={aiReconError()}>
                      <div class="mb-4 rounded-lg border border-red-200 bg-red-50 px-4 py-3 text-sm text-red-700" style="margin-bottom:14px">{aiReconError()}</div>
                    </Show>
                    <form onSubmit={handleAiReconcile} style="display:flex;flex-direction:column;gap:14px">
                      <div class="mt-4 grid grid-cols-1 gap-4 sm:grid-cols-2">
                        <div class="field">
                          <label style="display:block;font-size:13px;font-weight:600;margin-bottom:4px">Start Date</label>
                          <input
                            type="date"
                            required
                            value={aiReconFrom()}
                            onInput={(e) => setAiReconFrom(e.currentTarget.value)}
                            style="width:100%;padding:8px 10px;border:1px solid #e2e8f0;border-radius:6px;font-size:14px;box-sizing:border-box"
                          />
                        </div>
                        <div class="field">
                          <label style="display:block;font-size:13px;font-weight:600;margin-bottom:4px">End Date</label>
                          <input
                            type="date"
                            required
                            value={aiReconTo()}
                            onInput={(e) => setAiReconTo(e.currentTarget.value)}
                            style="width:100%;padding:8px 10px;border:1px solid #e2e8f0;border-radius:6px;font-size:14px;box-sizing:border-box"
                          />
                        </div>
                      </div>
                      <div>
                        <button class="btn-primary" type="submit" disabled={aiReconLoading()}>
                          {aiReconLoading() ? 'Running...' : 'Run Reconciliation'}
                        </button>
                      </div>
                    </form>
                  </section>

                  <Show when={aiReconResults() !== null}>
                    <div class="table-card">
                      <h3 style="margin:0 0 16px;font-size:15px;font-weight:700;color:#0f172a">Summary by Entry Type</h3>
                      <div class="overflow-x-auto">
                        <table class="data-table w-full text-sm">
                          <thead>
                            <tr>
                              <th>Entry Type</th>
                              <th>Count</th>
                              <th>Total Credits</th>
                            </tr>
                          </thead>
                          <tbody>
                            <For each={aiReconResults()?.summary || []}>
                              {(row) => (
                                <tr class="hover:bg-slate-50">
                                  <td class="font-semibold text-slate-900">{row.entry_type}</td>
                                  <td class="text-slate-700">{row.count}</td>
                                  <td class="text-slate-700">{row.total_credits}</td>
                                </tr>
                              )}
                            </For>
                          </tbody>
                        </table>
                      </div>

                      <h3 style="margin:24px 0 16px;font-size:15px;font-weight:700;color:#0f172a">Drift Check</h3>
                      <Show when={(aiReconResults()?.drift_check?.issues_found ?? 0) === 0}>
                        <p style="color:#16a34a;font-weight:600;font-size:14px;padding:16px">No discrepancies found. All wallets reconciled correctly.</p>
                      </Show>
                      <Show when={(aiReconResults()?.drift_check?.issues_found ?? 0) > 0}>
                        <div class="overflow-x-auto">
                          <table class="data-table w-full text-sm">
                            <thead>
                              <tr>
                                <th>User</th>
                                <th>Ledger Sum</th>
                                <th>Computed</th>
                                <th>Drift</th>
                              </tr>
                            </thead>
                            <tbody>
                              <For each={aiReconResults()?.drift_check?.issues || []}>
                                {(row) => (
                                  <tr class="hover:bg-slate-50">
                                    <td>
                                      <div class="font-semibold text-slate-900">{row.user_email}</div>
                                      <div style="font-size:11px;color:#64748b;font-family:monospace">{row.user_id}</div>
                                    </td>
                                    <td class="text-slate-700">{row.ledger_sum}</td>
                                    <td class="text-slate-700">{row.computed_available}</td>
                                    <td style={row.drift !== 0 ? 'color:#dc2626;font-weight:700' : 'color:#16a34a'}>
                                      {row.drift > 0 ? '+' : ''}{row.drift}
                                    </td>
                                  </tr>
                                )}
                              </For>
                            </tbody>
                          </table>
                        </div>
                      </Show>
                    </div>
                  </Show>
                </div>
              </Show>
            </div>
          </section>
        </Show>
      </div>
  );
}

function LedgerSection(props: {
  entries: AdminLedgerEntry[];
  onExport?: () => void;
  showUser?: boolean;
}) {
  return (
    <div>
      <div style="display:flex;align-items:center;gap:8px;padding:10px 14px;border-bottom:1px solid #F3F4F6">
        <h3 style="margin:0;font-size:14px;font-weight:700;color:#0f172a">TraceCoin Ledger</h3>
        <span style="font-size:12px;color:#94a3b8">{props.entries.length} entries</span>
        <Show when={props.onExport}>
          <button
            type="button"
            class="btn-secondary"
            style="margin-left:auto;padding:4px 10px;font-size:11px"
            onClick={props.onExport}
          >
            Export
          </button>
        </Show>
      </div>
      <Show
        when={props.entries.length > 0}
        fallback={
          <p style="padding:32px;text-align:center;color:#94a3b8;font-style:italic">
            No transactions found.
          </p>
        }
      >
        <div class="overflow-x-auto">
          <table class="data-table w-full text-sm">
            <thead>
              <tr>
                <Show when={props.showUser}>
                  <th>User</th>
                </Show>
                <th>Type</th>
                <th class="text-right">Amount</th>
                <th class="text-right">Balance After</th>
                <th>Reason</th>
                <th>Reference</th>
                <th>Date</th>
              </tr>
            </thead>
            <tbody>
              <For each={props.entries}>
                {(entry) => (
                  <tr class="hover:bg-slate-50">
                    <Show when={props.showUser}>
                      <td>
                        <div class="text-xs font-mono">{entry.user_id}</div>
                        <div class="text-xs text-slate-500">{entry.user_email ?? '—'}</div>
                      </td>
                    </Show>
                    <td>
                      <span
                        class={`inline-block px-2 py-0.5 rounded-full text-xs font-semibold ${entryTypeClass(entry.entry_type)}`}
                      >
                        {entry.entry_type}
                      </span>
                    </td>
                    <td
                      class="text-right font-semibold"
                      style={amountColor(entry.entry_type, entry.amount)}
                    >
                      {entry.amount > 0 ? '+' : ''}
                      {entry.amount}
                    </td>
                    <td class="text-right text-slate-700">
                      {entry.balance_after != null ? entry.balance_after : '—'}
                    </td>
                    <td class="text-slate-500 text-xs">{entry.reason ?? '—'}</td>
                    <td class="text-slate-500 text-xs font-mono">
                      {entry.reference_id ? entry.reference_id.substring(0, 12) + '…' : '—'}
                    </td>
                    <td class="text-slate-500 text-xs">
                      {new Date(entry.created_at).toLocaleString('en-IN')}
                    </td>
                  </tr>
                )}
              </For>
            </tbody>
          </table>
        </div>
      </Show>
    </div>
  );
}

function entryTypeClass(t: string): string {
  switch (t.toUpperCase()) {
    case 'CREDIT':
      return 'bg-green-100 text-green-700';
    case 'DEBIT':
      return 'bg-red-100 text-red-700';
    case 'RESERVE':
      return 'bg-amber-100 text-amber-700';
    case 'RELEASE':
      return 'bg-blue-100 text-blue-700';
    case 'ADJUSTMENT':
      return 'bg-purple-100 text-purple-700';
    default:
      return 'bg-gray-100 text-gray-700';
  }
}

function amountColor(type: string, amount: number): string {
  const credit = type.toUpperCase() === 'CREDIT' || type.toUpperCase() === 'RELEASE' || amount > 0;
  return credit ? 'color:#16a34a' : 'color:#dc2626';
}

function defaultFromDate(): string {
  const d = new Date();
  d.setDate(d.getDate() - 30);
  return toLocalIso(d);
}

function defaultToDate(): string {
  return toLocalIso(new Date());
}

function toLocalIso(d: Date): string {
  const pad = (n: number) => String(n).padStart(2, '0');
  return `${d.getFullYear()}-${pad(d.getMonth() + 1)}-${pad(d.getDate())}T${pad(d.getHours())}:${pad(d.getMinutes())}`;
}