<script lang="ts">
  import { ClipboardList, X } from 'lucide-svelte';

  import { api } from '$lib/api';
  import { toast } from '$lib/toast';
  import { tooltip } from '$lib/actions/tooltip';
  import { money, label, statusTone, ORDER_STATUSES } from '$lib/ordering/format';
  import type { Order } from '$lib/types';

  let { data } = $props();

  let orders = $state<Order[]>([]);
  $effect(() => {
    orders = data.orders ?? [];
  });

  let listQuery = $state('');
  const filteredOrders = $derived.by(() => {
    const q = listQuery.trim().toLowerCase();
    if (!q) return orders;
    return orders.filter((o) => {
      const ref = (o.order_number ?? `#${o.id}`).toLowerCase();
      return ref.includes(q) || (o.customer_name ?? '').toLowerCase().includes(q);
    });
  });

  let selectedOrder = $state<Order | null>(null);
  let statusChoice = $state('');

  async function openOrder(o: Order) {
    try {
      selectedOrder = await api.orderingAdmin.order(o.id);
      statusChoice = '';
    } catch (e) {
      toast.error(e instanceof Error ? e.message : 'Could not load order.');
    }
  }
  function closeOrder() {
    selectedOrder = null;
    statusChoice = '';
  }
  function handleWindowKeydown(event: KeyboardEvent) {
    if (event.key === 'Escape' && selectedOrder) closeOrder();
  }
  async function refreshOrders() {
    try {
      orders = await api.orderingAdmin.orders();
    } catch {}
  }
  async function applyStatus() {
    if (!selectedOrder || !statusChoice) return;
    try {
      selectedOrder = await api.orderingAdmin.updateStatus(selectedOrder.id, { to_status: statusChoice });
      toast.success(`Status set to ${label(statusChoice)}.`);
      statusChoice = '';
      await refreshOrders();
    } catch (e) {
      toast.error(e instanceof Error ? e.message : 'Status change rejected.');
    }
  }
  async function overrideLine(lineId: number, value: string) {
    if (!selectedOrder || value === '') return;
    try {
      selectedOrder = await api.orderingAdmin.overrideLine(selectedOrder.id, lineId, {
        unit_price: Number(value),
        reason: 'Admin override'
      });
      toast.success('Line price overridden.');
      await refreshOrders();
    } catch (e) {
      toast.error(e instanceof Error ? e.message : 'Override failed.');
    }
  }
  async function sendToXero() {
    if (!selectedOrder) return;
    try {
      selectedOrder = await api.orderingAdmin.sendToXero(selectedOrder.id);
      const r = selectedOrder.xero_result;
      toast.success(`Xero ${r?.status}${r?.stubbed ? ' (stub)' : ''}: ${r?.xero_invoice_id ?? ''}`);
      await refreshOrders();
    } catch (e) {
      toast.error(e instanceof Error ? e.message : 'Xero submission failed.');
    }
  }
  async function reopenOrder() {
    if (!selectedOrder) return;
    try {
      selectedOrder = await api.orderingAdmin.reopen(selectedOrder.id);
      toast.success('Order reopened to draft.');
      await refreshOrders();
    } catch (e) {
      toast.error(e instanceof Error ? e.message : 'Could not reopen.');
    }
  }
</script>

<svelte:window onkeydown={handleWindowKeydown} />

<div class="console-split">
  <!-- ── Left: order queue ─────────────────────────────────────────────────── -->
  <section class="surface-card">
    <div class="card-head">
      <h2>Orders <span class="count">{filteredOrders.length}</span></h2>
    </div>

    <input class="list-search" type="search" placeholder="Search order or customer" bind:value={listQuery} />

    {#if filteredOrders.length}
      <table class="clickable">
        <thead>
          <tr><th>Order</th><th>Status</th><th class="amt">Subtotal</th></tr>
        </thead>
        <tbody>
          {#each filteredOrders as o (o.id)}
            <tr
              class:selected={selectedOrder?.id === o.id}
              tabindex="0"
              role="button"
              aria-pressed={selectedOrder?.id === o.id}
              onclick={() => openOrder(o)}
              onkeydown={(e) => {
                if (e.key === 'Enter' || e.key === ' ') {
                  e.preventDefault();
                  openOrder(o);
                }
              }}
            >
              <td>
                <div class="id-cell">
                  <span class="id-name">{o.order_number ?? `#${o.id}`}</span>
                  <span class="id-sub">{o.customer_name ?? 'Unknown customer'}</span>
                </div>
              </td>
              <td><span class="pill {statusTone(o.status)}">{label(o.status)}</span></td>
              <td class="amt">{o.requires_quote ? 'Quote' : money(o.subtotal_ex_gst)}</td>
            </tr>
          {/each}
        </tbody>
      </table>
    {:else if orders.length}
      <p class="empty">No orders match “{listQuery}”.</p>
    {:else}
      <p class="empty">No submitted orders yet.</p>
    {/if}
  </section>

  <!-- ── Right: order detail ───────────────────────────────────────────────── -->
  {#if selectedOrder}
    <section class="surface-card detail workspace">
      <div class="workspace-head">
        <div class="detail-head head-row">
          <div class="detail-title">
            <p class="eyebrow">{selectedOrder.customer_name ?? 'Order'}</p>
            <h2>{selectedOrder.order_number ?? `Order #${selectedOrder.id}`}</h2>
          </div>
          <div class="detail-head-actions">
            <span class="pill {statusTone(selectedOrder.status)}">{label(selectedOrder.status)}</span>
            <button
              class="icon-btn"
              onclick={closeOrder}
              aria-label="Close order"
              use:tooltip={{ label: 'Close (Esc)', placement: 'bottom' }}
            >
              <X size={17} strokeWidth={2} aria-hidden="true" />
            </button>
          </div>
        </div>

        <div class="actions order-toolbar">
          <select bind:value={statusChoice} aria-label="Change status">
            <option value="">Change status…</option>
            {#each ORDER_STATUSES as s}<option value={s}>{label(s)}</option>{/each}
          </select>
          <button class="primary" onclick={applyStatus} disabled={!statusChoice}>Apply</button>
          <button class="secondary" onclick={sendToXero} use:tooltip={'Create or update the Xero invoice'}>Send to Xero</button>
          <button class="secondary" onclick={reopenOrder} use:tooltip={'Return this order to draft for editing'}>Reopen</button>
        </div>
      </div>

      <div class="workspace-body">
        <div class="meta">
          <div class="meta-item"><span>PO number</span><strong>{selectedOrder.purchase_order_number ?? '—'}</strong></div>
          <div class="meta-item"><span>Fulfilment</span><strong>{label(selectedOrder.fulfilment_method)}</strong></div>
          <div class="meta-item"><span>Xero</span><strong>{selectedOrder.xero_status ?? 'Not sent'}</strong></div>
        </div>

        <table class="lines">
          <thead>
            <tr><th>Product</th><th class="amt">Qty</th><th class="amt">Unit</th><th>Override</th><th class="amt">Total</th></tr>
          </thead>
          <tbody>
            {#each selectedOrder.lines as l (l.id)}
              <tr>
                <td>{l.product_name}</td>
                <td class="amt">{l.quantity}</td>
                <td class="amt">{l.requires_quote ? 'Quote' : money(l.resolved_unit_price ?? l.unit_price)}</td>
                <td>
                  <input
                    class="ovr"
                    type="number"
                    step="0.01"
                    placeholder={l.admin_override_price != null ? String(l.admin_override_price) : 'set'}
                    onchange={(e) => overrideLine(l.id, e.currentTarget.value)}
                  />
                </td>
                <td class="amt">{money(l.line_total)}</td>
              </tr>
            {/each}
          </tbody>
        </table>
        <div class="detail-total"><span>Subtotal (ex GST)</span><strong>{money(selectedOrder.subtotal_ex_gst)}</strong></div>

        {#if selectedOrder.status_history?.length}
          <details class="history">
            <summary>Status history ({selectedOrder.status_history.length})</summary>
            <ul>
              {#each selectedOrder.status_history as h}
                <li>
                  {label(h.from_status ?? 'new')} → {label(h.to_status)} ·
                  {h.actor_name ?? h.actor_type} ·
                  {new Date(h.created_at).toLocaleString('en-AU')}
                </li>
              {/each}
            </ul>
          </details>
        {/if}
      </div>
    </section>
  {:else}
    <section class="surface-card detail empty-detail">
      <span class="empty-icon" aria-hidden="true"><ClipboardList size={26} strokeWidth={1.7} /></span>
      <h2>Select an order</h2>
      <p class="muted">Choose an order from the queue to review its lines, adjust pricing, and move it through fulfilment.</p>
    </section>
  {/if}
</div>

<style>
  /* Right-align numeric columns for clean scanning. */
  .amt {
    text-align: right;
    font-variant-numeric: tabular-nums;
    white-space: nowrap;
  }

  .clickable tbody tr:focus-visible {
    outline: 2px solid var(--color-brand);
    outline-offset: -2px;
  }

  /* The header already carries the divider, so the title row drops its own. */
  .head-row {
    border-bottom: none;
    padding-bottom: 0;
    margin-bottom: 0.85rem;
  }
  .order-toolbar {
    margin-bottom: 0.9rem;
  }
</style>
