import { createSignal, createMemo, onMount, 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',
    ...(token ? { Authorization: `Bearer ${token}` } : {}),
  };
}

export default function InvoicePage() {
  const [invoices, setInvoices] = createSignal<any[]>([]);
  const [loading, setLoading] = createSignal(true);
  const [loadError, setLoadError] = createSignal('');
  const [search, setSearch] = createSignal('');
  const [statusFilter, setStatusFilter] = createSignal<'all' | 'paid' | 'pending' | 'failed'>('all');
  const [sortBy, setSortBy] = createSignal<'newest' | 'oldest' | 'total_desc' | 'total_asc'>('newest');
  const [sortMenuOpen, setSortMenuOpen] = createSignal(false);
  const [filterMenuOpen, setFilterMenuOpen] = createSignal(false);

  const load = async () => {
    setLoading(true); setLoadError('');
    try {
      const res = await fetch(`${API}/api/admin/invoices`, { headers: authHeaders(), credentials: 'include' });
      if (!res.ok) throw new Error(`Request failed (${res.status})`);
      const data = await res.json();
      setInvoices(Array.isArray(data) ? data : (data.invoices ?? []));
    } catch (err: any) {
      setLoadError(err.message || 'Could not load invoices.');
      setInvoices([]);
    } finally {
      setLoading(false);
    }
  };

  onMount(() => void load());

  const filteredInvoices = createMemo(() => {
    const q = search().toLowerCase();
    let data = invoices();
    if (q) {
      data = data.filter((inv) =>
        (inv.invoice_number || inv.id || '').toLowerCase().includes(q) ||
        (inv.user_id || '').toLowerCase().includes(q) ||
        (inv.package_name || '').toLowerCase().includes(q) ||
        (inv.status || '').toLowerCase().includes(q)
      );
    }
    if (statusFilter() !== 'all') {
      data = data.filter((inv) => {
        const st = String(inv.status || '').toLowerCase();
        if (statusFilter() === 'paid') return st === 'paid' || st === 'issued';
        if (statusFilter() === 'pending') return st === 'pending';
        if (statusFilter() === 'failed') return st === 'failed';
        return true;
      });
    }
    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 aTotal = Number(a.total ?? 0);
      const bTotal = Number(b.total ?? 0);
      if (sortBy() === 'oldest') return aCreated - bCreated;
      if (sortBy() === 'total_desc') return bTotal - aTotal;
      if (sortBy() === 'total_asc') return aTotal - bTotal;
      return bCreated - aCreated;
    });
    return sorted;
  });

  const exportCsv = () => {
    const headers = ['Invoice', 'User', 'Package', 'Total', 'Tax', 'Status', 'Date'];
    const rows = filteredInvoices().map((item) => [
      item.invoice_number || item.id,
      item.user_id || '—',
      item.package_name || '—',
      item.total != null ? `₹${(item.total / 100).toFixed(2)}` : '—',
      item.tax != null ? `₹${(item.tax / 100).toFixed(2)}` : '—',
      item.status || '—',
      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 = 'invoice-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]">Invoice Management</h1>
          <p class="mt-1 text-[14px] text-[#6B7280]">View and download all platform invoices.</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 invoices by number, user, package, or status..."
              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: 'total_desc', label: 'Total High-Low' },
                    { key: 'total_asc', label: 'Total Low-High' },
                  ] as { key: 'newest' | 'oldest' | 'total_desc' | 'total_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: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: 'all', label: 'All Status' },
                    { key: 'paid', label: 'Paid/Issued' },
                    { key: 'pending', label: 'Pending' },
                    { key: 'failed', label: 'Failed' },
                  ] as { key: 'all' | 'paid' | 'pending' | 'failed'; label: string }[]}>
                    {(item) => (
                      <button type="button" onClick={() => { setStatusFilter(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:${statusFilter() === item.key ? '#FF5E13' : '#374151'};background:${statusFilter() === 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>Invoice #</th>
                    <th>User</th>
                    <th>Package</th>
                    <th>Total (₹)</th>
                    <th>Tax (₹)</th>
                    <th>Status</th>
                    <th>Date</th>
                    <th class="text-right">Actions</th>
                  </tr>
                </thead>
                <tbody>
                  <Show when={loading()}>
                    <tr><td colspan="8" style="text-align:center;padding:32px;color:#64748b">Loading...</td></tr>
                  </Show>
                  <Show when={!loading() && loadError()}>
                    <tr><td colspan="8" style="text-align:center;padding:32px;color:#b91c1c">{loadError()}</td></tr>
                  </Show>
                  <Show when={!loading() && !loadError() && filteredInvoices().length === 0}>
                    <tr><td colspan="8" style="text-align:center;padding:32px;color:#94a3b8">No records found.</td></tr>
                  </Show>
                  <Show when={!loading() && !loadError() && filteredInvoices().length > 0}>
                    {filteredInvoices().map((item) => (
                      <tr class="hover:bg-slate-50">
                        <td class="font-semibold text-slate-900" style="font-family:monospace">{item.invoice_number || item.id}</td>
                        <td class="text-slate-500">{item.user_id || '—'}</td>
                        <td class="text-slate-500">{item.package_name || '—'}</td>
                        <td class="text-slate-500">₹{item.total != null ? (item.total / 100).toFixed(2) : '—'}</td>
                        <td class="text-slate-500">₹{item.tax != null ? (item.tax / 100).toFixed(2) : '—'}</td>
                        <td>
                          <span class={`inline-flex items-center rounded-full bg-gray-100 px-2.5 py-0.5 text-xs font-medium text-gray-600 ${item.status === 'PAID' || item.status === 'ISSUED' ? 'active' : ''}`}>
                            {item.status || '—'}
                          </span>
                        </td>
                        <td class="text-slate-500">{item.created_at ? new Date(item.created_at).toLocaleString() : '—'}</td>
                        <td>
                          <div class="flex items-center justify-end gap-1">
                            <Show when={item.download_url || item.pdf_url}>
                              <a
                                class="inline-flex items-center rounded-lg border border-gray-200 bg-white px-4 py-2 text-sm font-medium text-gray-700 hover:bg-gray-50 transition-colors"
                                href={item.download_url || item.pdf_url}
                                target="_blank"
                                rel="noopener noreferrer"
                                download
                              >
                                Download
                              </a>
                            </Show>
                            <Show when={!item.download_url && !item.pdf_url}>
                              <span style="color:#94a3b8;font-size:12px">—</span>
                            </Show>
                          </div>
                        </td>
                      </tr>
                    ))}
                  </Show>
                </tbody>
              </table>
            </div>
          </div>
          </div>
        </div>
      </div>
  );
}
