<script>
  import { enhance } from '$app/forms';
  import { locale, t, localized, formatMoney } from '$lib/i18n/store.js';

  export let data;
  export let form;
  $: lang = $locale;
  $: ({ invoice, lines, parts } = data);

  $: errors = form?.errors ?? {};

  // Add-a-part section state
  let partSearch = '';
  let partId     = '';
  let partQty    = '1';
  let partPrice  = '';

  $: filteredParts = (() => {
    const q = partSearch.trim().toLowerCase();
    if (!q) return parts;
    return parts.filter((p) =>
      (p.name_en || '').toLowerCase().includes(q) ||
      (p.name_tg || '').toLowerCase().includes(q) ||
      (p.barcode || '').toLowerCase().includes(q)
    );
  })();

  $: selectedPart = parts?.find((p) => String(p.id) === String(partId));
  $: visibleParts =
    selectedPart && !filteredParts.some((p) => p.id === selectedPart.id)
      ? [selectedPart, ...filteredParts]
      : filteredParts;

  // Auto-fill the unit-price input from the selected part's sale price,
  // unless the user has typed something different.
  let lastAutoPrice = '';
  $: {
    if (selectedPart) {
      const expected = selectedPart.sale_price
        ? (selectedPart.sale_price / 100).toFixed(2)
        : '';
      if (expected && (partPrice === '' || partPrice === lastAutoPrice)) {
        partPrice = expected;
        lastAutoPrice = expected;
      }
    }
  }

  // Add-custom-line state
  let customLabel = '';
  let customQty   = '1';
  let customPrice = '';

  $: runningTotalDirams = lines.reduce(
    (sum, l) => sum + (l.quantity * l.unit_price_dirams),
    0
  );

  function lineLabel(line) {
    if (line.affects_inventory === 0) return line.label;
    return localized({ name_en: line.part_name_en, name_tg: line.part_name_tg }, 'name', lang);
  }

  function confirmCancel(event) {
    if (!confirm($t('invoices.cancel_confirm'))) event.preventDefault();
  }
</script>

<h1 class="title">{$t('invoices.title')} <span class="muted">#{invoice.id}</span></h1>

{#if form?.errMsg}
  <div class="error">{form.errMsg}</div>
{/if}

<div class="builder">
  <div class="col left">
    <section class="card">
      <h2>{$t('invoices.add_part')}</h2>
      <form method="POST" action="?/add_part_line" class="stack" use:enhance>
        <label>
          {$t('movements.part')} *
          <input class="part-search"
                 type="search"
                 bind:value={partSearch}
                 placeholder={$t('parts.search_placeholder')} />
          <select name="part_id" bind:value={partId} required size={Math.min(6, Math.max(3, visibleParts.length + 1))}>
            <option value="">—</option>
            {#each visibleParts as p}
              <option value={String(p.id)}>
                {localized(p, 'name', lang)} ({$t('parts.quantity_on_hand')}: {p.quantity_on_hand})
              </option>
            {/each}
          </select>
          {#if partSearch && filteredParts.length === 0}
            <small class="muted">{$t('parts.no_results')}</small>
          {/if}
        </label>

        <div class="row">
          <label>
            {$t('movements.quantity')} *
            <input name="quantity" type="number" min="1" step="1" required bind:value={partQty} />
          </label>
          <label>
            {$t('movements.unit_price')} ({$t('common.currency_short')})
            <input name="unit_price" type="number" step="0.01" min="0" bind:value={partPrice} />
          </label>
        </div>

        {#if errors.add_part}
          <span class="field-error">{$t(errors.add_part)}</span>
        {/if}
        <div class="actions">
          <button type="submit">{$t('common.add')}</button>
        </div>
      </form>
    </section>

    <section class="card">
      <h2>{$t('invoices.add_custom')}</h2>
      <form method="POST" action="?/add_custom_line" class="stack" use:enhance>
        <label>
          {$t('invoices.custom_label')} *
          <input name="label" type="text" required bind:value={customLabel}
                 placeholder={$t('invoices.custom_placeholder')} />
        </label>
        <div class="row">
          <label>
            {$t('movements.quantity')} *
            <input name="quantity" type="number" min="1" step="1" required bind:value={customQty} />
          </label>
          <label>
            {$t('movements.unit_price')} ({$t('common.currency_short')})
            <input name="unit_price" type="number" step="0.01" min="0" bind:value={customPrice} />
          </label>
        </div>
        {#if errors.add_custom}
          <span class="field-error">{$t(errors.add_custom)}</span>
        {/if}
        <div class="actions">
          <button type="submit" class="secondary">{$t('common.add')}</button>
        </div>
      </form>
    </section>

  </div>

  <aside class="col right">
    <div class="running">
      <span class="muted">{$t('invoices.running_total')}</span>
      <strong class="total">{formatMoney(runningTotalDirams, lang)} {$t('common.currency_short')}</strong>
    </div>

    <section class="lines">
      <h2>{$t('invoices.lines')}</h2>
      {#if lines.length === 0}
        <p class="muted">{$t('invoices.no_lines')}</p>
      {:else}
        <table>
          <thead>
            <tr>
              <th>{$t('invoices.item')}</th>
              <th class="num">{$t('movements.quantity')}</th>
              <th class="num">{$t('movements.unit_price')}</th>
              <th class="num">{$t('invoices.line_total')}</th>
              <th></th>
            </tr>
          </thead>
          <tbody>
            {#each lines as line (line.id)}
              {@const lineTotal = line.quantity * line.unit_price_dirams}
              <tr>
                <td>
                  <div>{lineLabel(line)}</div>
                  {#if line.affects_inventory === 0}
                    <small class="muted">{$t('invoices.no_inventory_impact')}</small>
                  {/if}
                </td>
                <td class="num">
                  <form method="POST" action="?/update_line" class="inline" use:enhance>
                    <input type="hidden" name="line_id" value={line.id} />
                    <input type="hidden" name="unit_price" value={(line.unit_price_dirams / 100).toFixed(2)} />
                    <input name="quantity" type="number" min="1" step="1"
                           value={line.quantity} on:change={(e) => e.currentTarget.form.requestSubmit()} />
                  </form>
                  {#if errors[`line_${line.id}`]}
                    <small class="field-error">{$t(errors[`line_${line.id}`])}</small>
                  {/if}
                </td>
                <td class="num">
                  <form method="POST" action="?/update_line" class="inline" use:enhance>
                    <input type="hidden" name="line_id" value={line.id} />
                    <input type="hidden" name="quantity" value={line.quantity} />
                    <input name="unit_price" type="number" step="0.01" min="0"
                           value={(line.unit_price_dirams / 100).toFixed(2)}
                           on:change={(e) => e.currentTarget.form.requestSubmit()} />
                  </form>
                </td>
                <td class="num">{formatMoney(lineTotal, lang)}</td>
                <td>
                  <form method="POST" action="?/remove_line" class="inline" use:enhance>
                    <input type="hidden" name="line_id" value={line.id} />
                    <button type="submit" class="secondary remove" aria-label={$t('common.delete')}>×</button>
                  </form>
                </td>
              </tr>
            {/each}
          </tbody>
          <tfoot>
            <tr>
              <td colspan="3" class="num"><strong>{$t('common.total')}</strong></td>
              <td class="num"><strong>{formatMoney(runningTotalDirams, lang)} {$t('common.currency_short')}</strong></td>
              <td></td>
            </tr>
          </tfoot>
        </table>
      {/if}
    </section>

    {#if errors.save}
      <div class="error">{$t(errors.save)}</div>
    {/if}

    <section class="commit">
      <form method="POST" action="?/save_invoice" class="inline" use:enhance>
        <button type="submit" class="save">{$t('invoices.save')}</button>
      </form>
      <form method="POST" action="?/cancel_invoice" class="inline" on:submit={confirmCancel} use:enhance>
        <button type="submit" class="danger">{$t('invoices.cancel')}</button>
      </form>
    </section>
  </aside>
</div>

<style>
  .title { margin: 0 0 1rem; }
  .builder {
    display: grid;
    grid-template-columns: minmax(0, 1fr) minmax(0, 1.1fr);
    gap: 1.25rem;
    align-items: start;
  }
  .col { display: grid; gap: 1.25rem; }
  @media (max-width: 900px) {
    .builder { grid-template-columns: 1fr; }
  }
  .running {
    display: flex;
    align-items: baseline;
    justify-content: space-between;
    gap: 0.75rem;
    padding: 0.75rem 1.1rem;
    background: #fff;
    border: 2px solid #006a4e;
    border-radius: 8px;
    box-shadow: 0 1px 2px rgba(0,0,0,0.05);
  }
  .total {
    font-size: 1.35rem;
    color: #006a4e;
    font-variant-numeric: tabular-nums;
  }
  section.card { padding: 1rem 1.25rem; }
  section.card h2 { margin-top: 0; }
  .lines table { margin-top: 0.5rem; }
  .lines tfoot td { background: #f5f7fb; }
  .lines input[type=number] {
    width: 6rem;
    text-align: right;
    font-variant-numeric: tabular-nums;
  }
  form.inline { display: inline; }
  .part-search { margin-bottom: 0.35rem; }
  .field-error { color: #8a1f1b; font-size: 0.8rem; }
  .actions { display: flex; gap: 0.6rem; }
  .remove {
    padding: 0.15rem 0.55rem;
    font-size: 1.1rem;
    line-height: 1;
  }
  .commit {
    display: flex;
    gap: 0.75rem;
    align-items: center;
    padding-top: 0.75rem;
    border-top: 1px solid #e5e8ee;
  }
  .commit button.save {
    padding: 0.75rem 1.5rem;
    font-size: 1.05rem;
    font-weight: 600;
  }
</style>
