<script lang="ts">

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

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

  import type { Station } from "$lib/shared/model";
  import { ZStationNew } from "$lib/shared/model/validation";
  import { superformConfig } from "$lib/shared/util";

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

  const schema = zod(ZStationNew);

  export let station: Station | null = null;
  export let formData = defaults(schema);

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

<Header backHref="/stations" title={station ? `Station #${station.id}` : "Neue Station"} />

<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>

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