<script lang="ts">
  import { api } from '$lib/api';
  import { toast } from '$lib/toast';
  import type { OrderingNotificationSettings } from '$lib/types';

  let { data } = $props();

  let settings = $state<OrderingNotificationSettings | null>(null);
  $effect(() => {
    settings = data.settings ?? null;
  });

  async function saveSettings() {
    if (!settings) return;
    try {
      settings = await api.orderingAdmin.updateNotificationSettings(settings);
      toast.success('Settings saved.');
    } catch (e) {
      toast.error(e instanceof Error ? e.message : 'Could not save settings.');
    }
  }
</script>

<section class="surface-card">
  <h2>Notification settings</h2>
  {#if settings}
    <div class="form-grid">
      <label class="full">Internal recipients (comma separated)<input bind:value={settings.internal_recipients} /></label>
      <label class="full">From email<input bind:value={settings.from_email} /></label>
      <label class="check"><input type="checkbox" bind:checked={settings.send_customer_confirmation} /> Send customer confirmation</label>
      <label class="check"><input type="checkbox" bind:checked={settings.require_po_number} /> Require PO number on submit</label>
      <button class="primary" onclick={saveSettings}>Save settings</button>
    </div>
  {:else}
    <p class="empty">Could not load settings.</p>
  {/if}
</section>
