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

  export let data;
  export let form;
  $: lang = $locale;
  $: ({ part, categories, movements } = data);

  function confirmDelete(event) {
    const name = localized(part, 'name', lang) || String(part.id);
    const message = $t('parts.delete_confirm').replace('{name}', name);
    if (!confirm(message)) event.preventDefault();
  }

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

  // Display somoni (not dirams) in the form.
  function asSomoni(dirams) {
    if (dirams == null) return '';
    return (Number(dirams) / 100).toFixed(2);
  }
</script>

<div class="page-head">
  <h1>{$t('parts.edit')}: {localized(part, 'name', lang) || part.id}</h1>
  <a href="/parts" class="muted">← {$t('common.back')}</a>
</div>

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

<div class="layout">
  <section>
    <form class="stack" method="POST" action="?/update">
      <div class="row">
        <label>
          {$t('parts.name_en')}
          <input name="name_en" value={values.name_en ?? part.name_en} />
        </label>
        <label>
          {$t('parts.name_tg')}
          <input name="name_tg" value={values.name_tg ?? part.name_tg} />
        </label>
      </div>

      <label>
        {$t('parts.category')}
        <select name="category_id">
          <option value="">—</option>
          {#each categories as c}
            <option value={c.id}
              selected={String(values.category_id ?? part.category_id) === String(c.id)}>
              {localized(c, 'name', lang)}
            </option>
          {/each}
        </select>
      </label>

      <div class="row">
        <label>
          {$t('parts.cost_price')} ({$t('common.currency_short')})
          <input name="cost_price" type="number" step="0.01" min="0"
                 value={values.cost_price ?? asSomoni(part.cost_price)} />
        </label>
        <label>
          {$t('parts.sale_price')} ({$t('common.currency_short')})
          <input name="sale_price" type="number" step="0.01" min="0"
                 value={values.sale_price ?? asSomoni(part.sale_price)} />
        </label>
      </div>

      <div class="row">
        <label>
          {$t('parts.unit')}
          <input name="unit" value={values.unit ?? part.unit} />
        </label>
        <label>
          {$t('parts.reorder_level')}
          <input name="reorder_level" type="number" min="0" step="1"
                 value={values.reorder_level ?? part.reorder_level} />
        </label>
      </div>

      <label>
        {$t('parts.barcode')}
        <input name="barcode" value={values.barcode ?? part.barcode ?? ''} />
      </label>

      <label class="checkbox">
        <input type="checkbox" name="active" value="1"
               checked={values.active != null ? values.active === '1' : !!part.active} />
        {$t('parts.active')}
      </label>

      <div class="actions">
        <button type="submit">{$t('common.save')}</button>
        <a class="btn-link" href="/movements/new?part_id={part.id}">+ {$t('nav.new_movement')}</a>
      </div>
    </form>

    <form method="POST" action="?/delete" class="delete-form" use:enhance on:submit={confirmDelete}>
      <button type="submit" class="danger">{$t('common.delete')}</button>
    </form>
  </section>

  <aside>
    <div class="card">
      <div class="muted">{$t('parts.quantity_on_hand')}</div>
      <div class="qty" class:low={part.quantity_on_hand <= part.reorder_level}>
        {part.quantity_on_hand}
        <span class="unit">{part.unit}</span>
      </div>
      <div class="muted small">
        {$t('parts.reorder_level')}: {part.reorder_level}
      </div>
      <hr />
      <div class="muted small">{$t('common.created')}: {part.created_at}</div>
      <div class="muted small">{$t('common.updated')}: {part.updated_at}</div>
    </div>

    <h2>{$t('parts.recent_movements')}</h2>
    {#if movements.length === 0}
      <p class="muted">{$t('movements.no_movements')}</p>
    {:else}
      <table>
        <thead>
          <tr>
            <th>{$t('movements.created_at')}</th>
            <th>{$t('movements.type')}</th>
            <th class="num">{$t('movements.quantity')}</th>
            <th class="num">{$t('movements.unit_price')}</th>
          </tr>
        </thead>
        <tbody>
          {#each movements as m}
            <tr>
              <td>{m.created_at}</td>
              <td><span class="pill">{$t('movements.type_' + m.movement_type)}</span></td>
              <td class="num">{m.quantity > 0 ? '+' : ''}{m.quantity}</td>
              <td class="num">{m.unit_price != null ? formatMoney(m.unit_price, lang) : $t('common.none')}</td>
            </tr>
          {/each}
        </tbody>
      </table>
    {/if}
  </aside>
</div>

<style>
  .page-head { display: flex; justify-content: space-between; align-items: baseline; }
  .layout {
    display: grid;
    grid-template-columns: minmax(0, 1fr) 320px;
    gap: 1.5rem;
    align-items: start;
  }
  @media (max-width: 880px) {
    .layout { grid-template-columns: 1fr; }
  }
  .actions  { display: flex; gap: 1rem; align-items: center; }
  .btn-link {
    margin-left: auto;          /* push to the right edge of the form */
    background: #006a4e;
    color: #fff;
    padding: 0.5rem 1rem;
    border-radius: 4px;
    text-decoration: none;
    border: 1px solid transparent;
    font: inherit;
  }
  .btn-link:hover { background: #00553e; color: #fff; }
  .checkbox { display: flex; align-items: center; gap: 0.4rem; }
  .field-error { color: #8a1f1b; font-size: 0.8rem; }
  .delete-form {
    margin-top: 1.25rem;
    padding-top: 1rem;
    border-top: 1px solid #eef0f5;
  }

  .qty { font-size: 2rem; font-weight: 700; margin: 0.25rem 0; }
  .qty.low { color: #b8443f; }
  .qty .unit { font-size: 0.9rem; color: #6b7388; font-weight: 400; }
  .small { font-size: 0.8rem; }
  hr { border: 0; border-top: 1px solid #eef0f5; margin: 0.6rem 0; }
</style>
