<script lang="ts">
  import { tick } from 'svelte';
  import { Plus } from 'lucide-svelte';

  import { api } from '$lib/api';
  import { toast } from '$lib/toast';
  import { tooltip } from '$lib/actions/tooltip';
  import { label, PRODUCT_CATEGORIES } from '$lib/ordering/format';
  import type { CatalogueProduct } from '$lib/types';

  let { data } = $props();

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

  let listQuery = $state('');
  const filteredProducts = $derived.by(() => {
    const q = listQuery.trim().toLowerCase();
    if (!q) return products;
    return products.filter(
      (p) =>
        p.name.toLowerCase().includes(q) ||
        p.sku.toLowerCase().includes(q) ||
        label(p.category).toLowerCase().includes(q)
    );
  });

  const blankProduct = () => ({
    name: '',
    sku: '',
    category: 'grains',
    unit_of_measure: '20kg bag',
    min_order_quantity: 1,
    base_price: null as number | null,
    requires_quote: false,
    active: true
  });
  let newProduct = $state<Record<string, any>>(blankProduct());
  let showNewProduct = $state(false);
  let newProductNameInput: HTMLInputElement | null = $state(null);

  function toggleNewProduct() {
    showNewProduct = !showNewProduct;
    if (showNewProduct) newProduct = blankProduct();
  }
  $effect(() => {
    if (showNewProduct) tick().then(() => newProductNameInput?.focus());
  });

  async function refreshProducts() {
    try {
      products = await api.orderingAdmin.products();
    } catch {}
  }
  async function createProduct() {
    if (!newProduct.name || !newProduct.sku) return toast.error('Name and SKU are required.');
    try {
      await api.orderingAdmin.createProduct({
        ...newProduct,
        base_price:
          newProduct.base_price === null || newProduct.base_price === '' ? null : Number(newProduct.base_price)
      });
      toast.success('Product created.');
      newProduct = blankProduct();
      showNewProduct = false;
      await refreshProducts();
    } catch (e) {
      toast.error(e instanceof Error ? e.message : 'Could not create product.');
    }
  }
  async function toggleProductActive(p: CatalogueProduct) {
    try {
      await api.orderingAdmin.updateProduct(p.id, { active: !p.active });
      await refreshProducts();
    } catch (e) {
      toast.error(e instanceof Error ? e.message : 'Update failed.');
    }
  }
  async function saveProductPrice(p: CatalogueProduct, value: string) {
    try {
      await api.orderingAdmin.updateProduct(p.id, { base_price: value === '' ? null : Number(value) });
      toast.success('Base price updated.');
      await refreshProducts();
    } catch (e) {
      toast.error(e instanceof Error ? e.message : 'Update failed.');
    }
  }
</script>

<section class="surface-card">
  <div class="card-head">
    <h2>Catalogue <span class="count">{filteredProducts.length}</span></h2>
    <button class="primary" onclick={toggleNewProduct}>
      <Plus size={16} strokeWidth={2.2} aria-hidden="true" />
      {showNewProduct ? 'Cancel' : 'New product'}
    </button>
  </div>

  {#if showNewProduct}
    <div class="create-panel">
      <div class="form-grid">
        <label>Name<input bind:this={newProductNameInput} bind:value={newProduct.name} /></label>
        <label>SKU<input bind:value={newProduct.sku} /></label>
        <label>Category
          <select bind:value={newProduct.category}>
            {#each PRODUCT_CATEGORIES as c}<option value={c}>{label(c)}</option>{/each}
          </select>
        </label>
        <label>Unit of measure<input bind:value={newProduct.unit_of_measure} /></label>
        <label>Min order qty<input type="number" bind:value={newProduct.min_order_quantity} /></label>
        <label>Base price (ex GST)<input type="number" step="0.01" bind:value={newProduct.base_price} /></label>
        <label class="check full"><input type="checkbox" bind:checked={newProduct.requires_quote} /> Requires quote</label>
      </div>
      <div class="actions">
        <button class="secondary" onclick={toggleNewProduct}>Cancel</button>
        <button class="primary" onclick={createProduct}>Create product</button>
      </div>
    </div>
  {/if}

  <input class="list-search" type="search" placeholder="Search name, SKU, or category" bind:value={listQuery} />

  {#if filteredProducts.length}
    <table>
      <thead>
        <tr><th>Product</th><th>Category</th><th>Base price</th><th>Status</th><th></th></tr>
      </thead>
      <tbody>
        {#each filteredProducts as p (p.id)}
          <tr class:dimmed={!p.active}>
            <td>
              <div class="id-cell">
                <span class="id-name">{p.name}{#if p.requires_quote}<span class="tag">quote</span>{/if}</span>
                <span class="id-sub">{p.sku} · {p.unit_of_measure}</span>
              </div>
            </td>
            <td>{label(p.category)}</td>
            <td>
              {#if p.requires_quote}
                <span class="by-quote">By quote</span>
              {:else}
                <span class="price-field">
                  <span class="price-prefix">$</span>
                  <input
                    class="inline price-input"
                    type="number"
                    step="0.01"
                    value={p.base_price ?? ''}
                    placeholder="0.00"
                    onchange={(e) => saveProductPrice(p, e.currentTarget.value)}
                  />
                </span>
              {/if}
            </td>
            <td><span class="pill {p.active ? 'pos' : 'muted-pill'}">{p.active ? 'Active' : 'Disabled'}</span></td>
            <td class="row-action">
              <button
                class="link"
                onclick={() => toggleProductActive(p)}
                use:tooltip={p.active ? 'Hide from all customer catalogues' : 'Make orderable again'}
              >
                {p.active ? 'Disable' : 'Enable'}
              </button>
            </td>
          </tr>
        {/each}
      </tbody>
    </table>
  {:else if products.length}
    <p class="empty">No products match “{listQuery}”.</p>
  {:else}
    <p class="empty">No products yet. Create one to build the catalogue.</p>
  {/if}
</section>

<style>
  .primary { gap: 0.4rem; }
  .primary :global(svg) { display: block; }

  /* Inactive rows read as muted without disappearing. */
  tr.dimmed .id-name,
  tr.dimmed td { color: var(--color-text-muted); }

  .by-quote {
    font-size: 0.78rem;
    color: var(--color-text-muted);
    font-style: italic;
  }

  .price-field {
    display: inline-flex;
    align-items: center;
    gap: 0.15rem;
  }
  .price-prefix {
    color: var(--color-text-muted);
    font-size: 0.82rem;
  }
  .price-input {
    width: 5.5rem;
    font-variant-numeric: tabular-nums;
  }

  .row-action {
    text-align: right;
    white-space: nowrap;
  }
</style>
