<script lang="ts">

  import { browser } from "$app/environment";

  import { defaults, superForm } from "sveltekit-superforms";
  import { zod } from "sveltekit-superforms/adapters";

  import { ZRoomNew } from "$lib/shared/model/validation";
  import { trpc, type RouterOutput } from "$lib/shared/trpc";
  import { superformConfig } from "$lib/shared/util";

  import Autocomplete from "$lib/components/filter/Autocomplete.svelte";
  import FormField from "$lib/components/ui/FormField.svelte";
  import Header from "$lib/components/ui/Header.svelte";

  const schema = zod(ZRoomNew);

  export let room: RouterOutput["room"]["get"] | null = null;
  export let formData = defaults(schema);

  const {
    form, errors, constraints, enhance, tainted,
  } = superForm(formData, {
    validators: schema,
    resetForm: room === null,
    ...superformConfig("Zimmer"),
  });
</script>

<Header backHref="/rooms" title={room ? `Zimmer #${room.id}` : "Neues Zimmer"} />

<form class="flex flex-col gap-4" method="POST" use:enhance>
  <FormField errors={$errors.name} label="Name">
    <input
      name="name"
      aria-invalid={Boolean($errors.name)}
      type="text"
      bind:value={$form.name}
      {...$constraints.name}
    />
  </FormField>

  <FormField errors={$errors.station_id} label="Station">
    <Autocomplete
      idInputName="station_id"
      inputCls="input input-bordered w-full max-w-xs"
      items={async () => trpc().station.list.query()}
      onSelect={(item) => {
        $form.station_id = item.id;
      }}
      onUnselect={() => {
        $form.station_id = 0;
      }}
      selection={room?.station}
    />
  </FormField>

  <div class="flex flex-wrap gap-2">
    <button
      class="btn btn-primary max-w-32"
      disabled={browser && room && $tainted === undefined}
      type="submit"
    >
      Speichern
    </button>
    <slot />
  </div>
</form>
