import { createMemo, createResource, createSignal, Show, For } from 'solid-js';

const API = '';

function getToken(): string {
  return typeof sessionStorage !== "undefined"
    ? sessionStorage.getItem("nxtgauge_admin_access_token") || ""
    : "";
}

function authHeaders(): Record<string, string> {
  const token = getToken();
  return {
    Accept: "application/json",
    "Content-Type": "application/json",
    ...(token ? { Authorization: `Bearer ${token}` } : {}),
  };
}

type LedgerEntry = {
  id: string;
  entry_type: string;
  amount: number;
  balance_after: number | null;
  reason: string | null;
  reference_id: string | null;
  actor_user_id: string | null;
  metadata: any;
  created_at: string;
  user_id: string;
  user_email: string | null;
};

async function loadLedger(): Promise<LedgerEntry[]> {
  try {
    const res = await fetch(`${API}/api/admin/ledger?page=1&limit=100`, {
      headers: authHeaders(),
      credentials: "include",
    });
    if (!res.ok) throw new Error('Failed to load');
    const data = await res.json();
    return Array.isArray(data) ? data : (data.entries || data.ledger || []);
  } catch {
    return [];
  }
}

function typeBadgeStyle(entryType: string): string {
  switch ((entryType || '').toUpperCase()) {
    case 'CREDIT':
      return 'background:#dcfce7;color:#166534;border-color:#bbf7d0';
    case 'DEBIT':
      return 'background:#fee2e2;color:#991b1b;border-color:#fecaca';
    case 'RESERVE':
      return 'background:#fff7ed;color:#c2410c;border-color:#fed7aa';
    case 'RELEASE':
      return 'background:#dbeafe;color:#1d4ed8;border-color:#bfdbfe';
    case 'ADJUSTMENT':
      return 'background:#f3e8ff;color:#7e22ce;border-color:#e9d5ff';
    default:
      return 'background:#f1f5f9;color:#475569;border-color:#e2e8f0';
  }
}

function formatAmount(entry: LedgerEntry): string {
  if (entry.amount == null) return '—';
  const sign = entry.amount >= 0 ? '+' : '';
  return `${sign}${entry.amount} TC`;
}

export default function LedgerPage() {
  const [entries] = createResource(loadLedger);
  const [search, setSearch] = createSignal('');
  const [typeFilter, setTypeFilter] = createSignal<'all' | 'CREDIT' | 'DEBIT' | 'RESERVE' | 'RELEASE' | 'ADJUSTMENT'>('all');
  const [sortBy, setSortBy] = createSignal<'newest' | 'oldest' | 'amount_desc' | 'amount_asc'>('newest');
  const [sortMenuOpen, setSortMenuOpen] = createSignal(false);
  const [filterMenuOpen, setFilterMenuOpen] = createSignal(false);

  const filteredEntries = createMemo(() => {
    let data = entries() ?? [];
    const q = search().toLowerCase().trim();
    if (q) {
      data = data.filter((item) => {
        const t = String(item.entry_type || '').toLowerCase();
        return t.includes(q)
          || String(item.user_email || '').toLowerCase().includes(q)
          || String(item.user_id || '').toLowerCase().includes(q)
          || String(item.reason || '').toLowerCase().includes(q)
          || String(item.reference_id || '').toLowerCase().includes(q);
      });
    }
    if (typeFilter() !== 'all') {
      data = data.filter((item) => String(item.entry_type || '').toUpperCase() === typeFilter());
    }
    const sorted = [...data];
    sorted.sort((a, b) => {
      const aCreated = new Date(a.created_at || 0).getTime();
      const bCreated = new Date(b.created_at || 0).getTime();
      const aAmt = Number(a.amount ?? 0);
      const bAmt = Number(b.amount ?? 0);
      if (sortBy() === 'oldest') return aCreated - bCreated;
      if (sortBy() === 'amount_desc') return bAmt - aAmt;
      if (sortBy() === 'amount_asc') return aAmt - bAmt;
      return bCreated - aCreated;
    });
    return sorted;
  });

  const exportCsv = () => {
    const headers = ['Type', 'User', 'Amount', 'Balance After', 'Reason', 'Reference', 'Date'];
    const rows = filteredEntries().map((item) => [
      item.entry_type || '—',
      item.user_email || '—',
      formatAmount(item),
      item.balance_after != null ? String(item.balance_after) : '—',
      item.reason || '—',
      item.reference_id || '—',
      item.created_at ? new Date(item.created_at).toLocaleString() : '—',
    ]);
    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 = 'ledger-management.csv';
    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]">Ledger Management</h1>
          <p class="mt-1 text-[14px] text-[#6B7280]">Platform financial ledger</p>
        </div>

        <div>
          <div style="position:relative;margin-top:1.5rem;margin-left:-24px;margin-right:-24px;border-radius:0;border-left:none;border-right:none;overflow:visible;border-top:1px solid #E5E7EB;border-bottom:1px solid #E5E7EB;background:white;box-shadow:0 1px 3px rgba(0,0,0,0.06)">
          <div style="display:flex;align-items:center;gap:8px;padding:14px 20px;border-bottom:1px solid #F3F4F6;position:relative;z-index:20;margin-bottom:0">
            <input
              type="text"
              placeholder="Search by type, order, invoice, user, or note..."
              value={search()}
              onInput={(e) => setSearch(e.currentTarget.value)}
              style="height:34px;flex:1;border-radius:8px;border:1px solid #E5E7EB;background:white;padding:0 12px;font-size:13px;color:#111827;outline:none"
            />
            <div style="position:relative;">
              <button type="button" onClick={() => { setSortMenuOpen((v) => !v); setFilterMenuOpen(false); }} style="display:inline-flex;height:34px;align-items:center;gap:6px;border-radius:8px;border:1px solid #E5E7EB;background:white;padding:0 12px;font-size:12px;font-weight:500;color:#374151;cursor:pointer">
                <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M7 4v13"/><path d="m3 13 4 4 4-4"/><path d="M17 20V7"/><path d="m21 11-4-4-4 4"/></svg>
                Sort
              </button>
              <Show when={sortMenuOpen()}>
                <div style="position:absolute;right:0;top:38px;z-index:40;min-width:180px;border:1px solid #E5E7EB;border-radius:12px;background:#fff;box-shadow:0 12px 24px rgba(2,6,23,0.12);padding:8px">
                  <For each={[
                    { key: 'newest', label: 'Newest First' },
                    { key: 'oldest', label: 'Oldest First' },
                    { key: 'amount_desc', label: 'Amount High-Low' },
                    { key: 'amount_asc', label: 'Amount Low-High' },
                  ] as { key: 'newest' | 'oldest' | 'amount_desc' | 'amount_asc'; label: string }[]}>
                    {(item) => (
                      <button type="button" onClick={() => { setSortBy(item.key); setSortMenuOpen(false); }} style={`display:block;width:100%;border-radius:8px;padding:8px 12px;text-align:left;font-size:13px;background:none;border:none;cursor:pointer;color:${sortBy() === item.key ? '#FF5E13' : '#374151'};background:${sortBy() === item.key ? '#FFF1EB' : 'transparent'}`}>{item.label}</button>
                    )}
                  </For>
                </div>
              </Show>
            </div>
            <div style="position:relative;">
              <button type="button" onClick={() => { setFilterMenuOpen((v) => !v); setSortMenuOpen(false); }} style="display:inline-flex;height:34px;align-items:center;gap:6px;border-radius:8px;border:1px solid #E5E7EB;background:white;padding:0 12px;font-size:12px;font-weight:500;color:#374151;cursor:pointer">
                <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M3 5h18M6 12h12M10 19h4"/></svg>
                Filters
              </button>
              <Show when={filterMenuOpen()}>
                <div style="position:absolute;right:0;top:38px;z-index:40;min-width:170px;border:1px solid #E5E7EB;border-radius:12px;background:#fff;box-shadow:0 12px 24px rgba(2,6,23,0.12);padding:8px">
                  <For each={[
                    { key: 'all', label: 'All Types' },
                    { key: 'CREDIT', label: 'Credit' },
                    { key: 'DEBIT', label: 'Debit' },
                    { key: 'RESERVE', label: 'Reserve' },
                    { key: 'RELEASE', label: 'Release' },
                    { key: 'ADJUSTMENT', label: 'Adjustment' },
                  ] as { key: 'all' | 'CREDIT' | 'DEBIT' | 'RESERVE' | 'RELEASE' | 'ADJUSTMENT'; label: string }[]}>
                    {(item) => (
                      <button type="button" onClick={() => { setTypeFilter(item.key); setFilterMenuOpen(false); }} style={`display:block;width:100%;border-radius:8px;padding:8px 12px;text-align:left;font-size:13px;background:none;border:none;cursor:pointer;color:${typeFilter() === item.key ? '#FF5E13' : '#374151'};background:${typeFilter() === item.key ? '#FFF1EB' : 'transparent'}`}>{item.label}</button>
                    )}
                  </For>
                </div>
              </Show>
            </div>
            <button type="button" onClick={exportCsv} style="display:inline-flex;height:34px;align-items:center;gap:6px;border-radius:8px;background:#0D0D2A;padding:0 12px;font-size:12px;font-weight:600;color:white;border:none;cursor:pointer">
              <svg width="13" height="13" viewBox="0 0 24 24" fill="none" stroke="currentColor" stroke-width="2"><path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4"/><polyline points="7 10 12 15 17 10"/><line x1="12" y1="15" x2="12" y2="3"/></svg>
              Export
            </button>
          </div>
          <div class="table-card">
            <div class="overflow-x-auto">
              <table class="data-table w-full text-sm">
                <thead>
                  <tr>
                    <th>Type</th>
                    <th>User</th>
                    <th>Amount</th>
                    <th>Balance After</th>
                    <th>Reason</th>
                    <th>Reference</th>
                    <th>Date</th>
                  </tr>
                </thead>
                <tbody>
                  <Show when={entries.loading}>
                    <tr><td colspan="7" style="text-align:center;padding:32px;color:#64748b">Loading...</td></tr>
                  </Show>
                  <Show when={!entries.loading && entries.error}>
                    <tr><td colspan="7" style="text-align:center;padding:32px;color:#b91c1c">Failed to load. Is the backend running?</td></tr>
                  </Show>
                  <Show when={!entries.loading && !entries.error && filteredEntries().length === 0}>
                    <tr><td colspan="7" style="text-align:center;padding:32px;color:#94a3b8">No ledger entries found.</td></tr>
                  </Show>
                  <Show when={!entries.loading && !entries.error && filteredEntries().length > 0}>
                    <For each={filteredEntries()}>
                      {(item) => {
                        const entryType = item.entry_type || '—';
                        return (
                          <tr class="hover:bg-slate-50">
                            <td>
                              <span style={`${typeBadgeStyle(entryType)};padding:2px 10px;border-radius:999px;font-size:12px;font-weight:600;border:1px solid;display:inline-block`}>
                                {entryType}
                              </span>
                            </td>
                            <td class="text-slate-500">
                              <div class="text-xs">{item.user_email || '—'}</div>
                              <div class="text-xs font-mono text-slate-400">{item.user_id?.substring(0, 8) ?? '—'}…</div>
                            </td>
                            <td class="font-semibold" style={item.amount >= 0 ? 'color:#16a34a' : 'color:#dc2626'}>
                              {formatAmount(item)}
                            </td>
                            <td class="text-slate-700">{item.balance_after != null ? item.balance_after : '—'}</td>
                            <td class="text-slate-500 text-xs">{item.reason || '—'}</td>
                            <td class="text-slate-500 text-xs font-mono">
                              {item.reference_id ? item.reference_id.substring(0, 8) + '…' : '—'}
                            </td>
                            <td class="text-slate-500">{item.created_at ? new Date(item.created_at).toLocaleString() : '—'}</td>
                          </tr>
                        );
                      }}
                    </For>
                  </Show>
                </tbody>
              </table>
            </div>
            <Show when={!entries.loading && !entries.error && filteredEntries().length > 0}>
              <div style="display:flex;align-items:center;justify-content:space-between;border-top:1px solid #F3F4F6;padding:12px 20px">
                <p style="font-size:13px;color:#6B7280">
                  Showing <strong style="font-weight:600;color:#111827">1–{filteredEntries().length}</strong> of <strong style="font-weight:600;color:#111827">{filteredEntries().length}</strong> ledger entries
                </p>
                <div style="display:flex;align-items:center;gap:4px">
                  <button type="button" style="display:inline-flex;width:30px;height:30px;align-items:center;justify-content:center;border-radius:7px;border:1px solid #E5E7EB;background:white;color:#6B7280;cursor:pointer;font-size:15px">‹</button>
                  <button type="button" style="display:inline-flex;width:30px;height:30px;align-items:center;justify-content:center;border-radius:7px;background:#FF5E13;color:white;font-size:13px;font-weight:600;border:none;cursor:pointer">1</button>
                  <button type="button" style="display:inline-flex;width:30px;height:30px;align-items:center;justify-content:center;border-radius:7px;border:1px solid #E5E7EB;background:white;color:#374151;font-size:13px;font-weight:500;cursor:pointer">2</button>
                  <button type="button" style="display:inline-flex;width:30px;height:30px;align-items:center;justify-content:center;border-radius:7px;border:1px solid #E5E7EB;background:white;color:#374151;font-size:13px;font-weight:500;cursor:pointer">3</button>
                  <button type="button" style="display:inline-flex;width:30px;height:30px;align-items:center;justify-content:center;border-radius:7px;border:1px solid #E5E7EB;background:white;color:#6B7280;cursor:pointer;font-size:15px">›</button>
                </div>
              </div>
            </Show>
          </div>
          </div>
        </div>
      </div>
  );
}
