import { createResource, createSignal, createMemo, 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 Order = {
  id: string;
  reference_number: string;
  payu_txnid?: string;
  amount_inr: number;
  tracecoins_credited: number;
  status: string;
  issued_at?: string;
  paid_at?: string | null;
  created_at?: string;
  user_id: string;
  user_email?: string | null;
  package_name?: string | null;
};

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

function statusClass(status: string): string {
  const s = (status || '').toUpperCase();
  if (s === 'PAID' || s === 'COMPLETED' || s === 'SUCCESS') return 'active';
  if (s === 'PENDING') return 'pending';
  if (s === 'FAILED') return 'failed';
  if (s === 'REFUNDED' || s === 'VOID') return 'inactive';
  return '';
}

function statusStyle(status: string): string {
  const s = (status || '').toUpperCase();
  if (s === 'PAID' || s === 'COMPLETED' || s === 'SUCCESS') return 'background:#dcfce7;color:#166534;border-color:#bbf7d0';
  if (s === 'PENDING') return 'background:#fff7ed;color:#c2410c;border-color:#fed7aa';
  if (s === 'FAILED') return 'background:#fee2e2;color:#991b1b;border-color:#fecaca';
  if (s === 'REFUNDED' || s === 'VOID') return 'background:#f1f5f9;color:#475569;border-color:#e2e8f0';
  return '';
}

export default function OrderPage() {
  const [orders] = createResource(loadOrders);
  const [search, setSearch] = createSignal('');
  const [statusFilter, setStatusFilter] = createSignal<'all' | 'paid' | 'pending' | 'failed'>('all');
  const [sortBy, setSortBy] = createSignal<'newest' | 'oldest' | 'amount_desc' | 'amount_asc'>('newest');
  const [sortMenuOpen, setSortMenuOpen] = createSignal(false);
  const [filterMenuOpen, setFilterMenuOpen] = createSignal(false);

  const filtered = createMemo(() => {
    const q = search().toLowerCase().trim();
    let data = orders() ?? [];
    if (q) {
      data = data.filter((o) => {
        const txn = (o.payu_txnid || o.reference_number || '').toLowerCase();
        const email = (o.user_email || '').toLowerCase();
        const pkg = (o.package_name || '').toLowerCase();
        const status = (o.status || '').toLowerCase();
        return txn.includes(q) || email.includes(q) || pkg.includes(q) || status.includes(q);
      });
    }
    if (statusFilter() !== 'all') {
      data = data.filter((o) => {
        const st = (o.status || '').toUpperCase();
        if (statusFilter() === 'paid') return st === 'PAID' || st === 'COMPLETED' || st === 'SUCCESS';
        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 || a.issued_at || 0).getTime();
      const bCreated = new Date(b.created_at || b.issued_at || 0).getTime();
      const aAmt = Number(a.amount_inr ?? 0);
      const bAmt = Number(b.amount_inr ?? 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 = ['Order', 'User Email', 'Package', 'TraceCoins', 'Total', 'Status', 'Created'];
    const rows = filtered().map((item) => [
      item.payu_txnid || item.reference_number,
      item.user_email || '—',
      item.package_name || '—',
      item.tracecoins_credited ?? '—',
      formatAmount(item),
      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 = 'order-management.csv';
    link.click();
    URL.revokeObjectURL(url);
  };

  const formatAmount = (order: Order) => {
    if (order.amount_inr == null) return '—';
    return `₹${(order.amount_inr / 100).toFixed(2)}`;
  };

  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]">Order Management</h1>
          <p class="mt-1 text-[14px] text-[#6B7280]">TraceCoin package purchase orders</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 order number, user email, 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: '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: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/Completed' },
                    { 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>Order #</th>
                    <th>User</th>
                    <th>Package</th>
                    <th>TraceCoins</th>
                    <th>Total</th>
                    <th>Status</th>
                    <th>Created At</th>
                  </tr>
                </thead>
                <tbody>
                  <Show when={orders.loading}>
                    <tr><td colspan="7" style="text-align:center;padding:32px;color:#64748b">Loading...</td></tr>
                  </Show>
                  <Show when={!orders.loading && orders.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={!orders.loading && !orders.error && filtered().length === 0}>
                    <tr><td colspan="7" style="text-align:center;padding:32px;color:#94a3b8">No orders found.</td></tr>
                  </Show>
                  <Show when={!orders.loading && !orders.error && filtered().length > 0}>
                    <For each={filtered()}>
                      {(item) => (
                        <tr class="hover:bg-slate-50">
                          <td class="font-semibold text-slate-900" style="font-family:monospace">
                            {item.payu_txnid || item.reference_number}
                          </td>
                          <td class="text-slate-500">{item.user_email || '—'}</td>
                          <td class="text-slate-500">{item.package_name || '—'}</td>
                          <td class="text-slate-500">{item.tracecoins_credited ?? '—'}</td>
                          <td class="text-slate-500">{formatAmount(item)}</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"
                              style={`${statusStyle(item.status)};padding:2px 10px;border-radius:999px;font-size:12px;font-weight:600;border:1px solid`}
                            >
                              {item.status || '—'}
                            </span>
                          </td>
                          <td class="text-slate-500">
                            {item.created_at
                              ? new Date(item.created_at).toLocaleString()
                              : item.issued_at
                                ? new Date(item.issued_at).toLocaleString()
                                : '—'}
                          </td>
                        </tr>
                      )}
                    </For>
                  </Show>
                </tbody>
              </table>
            </div>
          </div>
          </div>
        </div>
      </div>
  );
}
