<script>
  import { store } from '$lib/v2/globalStore.svelte.js';
  import ListPage from '$lib/v2/snippets/ListPage.svelte';
  import { Toast } from '$lib/v2/toast/notification.js';
  import ResCard from '$lib/v2/ui/ResCard.svelte';
  import { untrack } from 'svelte';
  import IconCheck from '~icons/tabler/check';
  import IconX from '~icons/tabler/x';

  let { data, form } = $props();

  store.pageTitle = 'Listing all devices';

  $effect(() => {
    if (form?.error && !form.success) {
      untrack(() => {
        Toast.add({ Icon: IconX, content: form.error, theme: 'error' });
      });
    } else if (form?.success) {
      untrack(() => {
        Toast.add({
          Icon: IconCheck,
          content: `Sent magic packets to ${form.deviceName}.`,
          theme: 'success',
        });
      });
    }
  });
</script>

<ListPage
  createHref={data.user.admin ? '/dash/devices/new' : null}
  empty={data.devices.length == 0}
  msgAdd="Add Device"
>
  <div class="flex gap-4 flex-wrap justify-center">
    {#each data.devices as device}
      <ResCard
        title={device.name}
        subtitle={device.mac}
        editHref={data.user.admin ? `/dash/devices/${device.id}` : null}
        wakeId={device.id}
      />
    {/each}
  </div>
</ListPage>
