<script lang="ts">
  import { browser } from "$app/environment";
  import { goto } from "$app/navigation";
  import type { PageData } from "./$types";

  import { mdiCalendar, mdiDomain } from "@mdi/js";

  import { URL_VISIT } from "$lib/shared/constants";
  import type { PaginationRequest, Station } from "$lib/shared/model";
  import { trpc } from "$lib/shared/trpc";
  import {
    DateRange, dateFromYMD, getQueryUrl, humanDate,
  } from "$lib/shared/util";

  import Autocomplete from "$lib/components/filter/Autocomplete.svelte";
  import EntryCard from "$lib/components/ui/EntryCard.svelte";
  import IconButton from "$lib/components/ui/IconButton.svelte";
  import PaginationButtons from "$lib/components/ui/PaginationButtons.svelte";
  import WeekSelector from "$lib/components/ui/WeekSelector.svelte";

  export let data: PageData;

  let dateRange: DateRange;
  let selection: Station | null;

  $: if (data.query.filter?.date) {
    const date = data.query.filter?.date[0];
    if (date) {
      dateRange = DateRange.parse(date.id) ?? DateRange.thisWeek();
    } else {
      dateRange = DateRange.thisWeek();
    }
  } else {
    dateRange = DateRange.thisWeek();
  }

  $: if (data.query.filter?.station) {
    const station = data.query.filter?.station[0];
    if (station) {
      selection = { id: station.id, name: station.name ?? "" };
    } else {
      selection = null;
    }
  } else {
    selection = null;
  }

  $: groupByStation = data.query.group === "station";

  function paginationUpdate(pagination: PaginationRequest): void {
    updateQuery({
      filter: data.query.filter,
      group: data.query.group,
      pagination,
    });
  }

  function filterUpdate(): void {
    updateQuery({
      filter: {
        done: false,
        station: selection ? [selection] : undefined,
        date: dateRange ? [{ id: dateRange.toString() }] : undefined,
      },
      group: data.query.group,
    });
  }

  function toggleGroup(): void {
    updateQuery({
      ...data.query,
      group: groupByStation ? undefined : "station",
    });
  }

  function updateQuery(q: typeof data.query): void {
    if (browser) {
      // Update page URL
      const url = getQueryUrl(q, URL_VISIT);
      void goto(url, { replaceState: true, keepFocus: true });
    }
  }
</script>

<svelte:head>
  <title>Visite {dateRange.format()}</title>
</svelte:head>

<div class="flex gap-4 items-baseline">
  <h1 class="heading">Visite</h1>
  <span class="hidden print:block">{dateRange.format()}</span>
</div>

<div class="flex flex-wrap gap-2 justify-between print:hidden">
  <div class="flex gap-2 items-center">
    <!-- <span>Zeitraum:</span> -->
    <WeekSelector onSelect={filterUpdate} bind:dateRange />
  </div>

  <div class="flex flex-wrap gap-2">
    <div class="flex items-center gap-2">
      <span>Gruppierung:</span>
      <IconButton
        path={groupByStation ? mdiDomain : mdiCalendar}
        title={groupByStation ? "Station" : "Datum"}
        on:click={toggleGroup} />
    </div>
    <div class="flex items-center gap-2">
      <span>Station:</span>
      <Autocomplete
        clearBtn
        inputCls="input input-sm input-bordered"
        items={async () => trpc().station.list.query()}
        onSelect={filterUpdate}
        onUnselect={filterUpdate}
        bind:selection />
    </div>
  </div>
</div>

<div class="flex flex-col gap-4">
  {#each data.groups as group}
    {@const first = group.items[0] ?? group.prio[0]}
    <div class="bg-base-content/15 rounded-xl px-2 font-bold print:hidden">
      {#if data.groupByStation}
        {#if first.patient.room}
          Station {first.patient.room?.station.name}
        {:else}
          Keine Station
        {/if}
      {:else}
        {humanDate(dateFromYMD(first.current_version.date), false, true)}
      {/if}
    </div>
    {#each group.prio as entry}
      <EntryCard {entry} />
    {/each}
    {#each group.items as entry}
      <EntryCard {entry} />
    {/each}
  {/each}
</div>

<PaginationButtons
  data={data.pagination}
  onUpdate={paginationUpdate}
  paginationData={data.query.pagination}
/>
