<script setup lang="ts">
  import { Effect, pipe } from "effect";
  import { useTemplateRef } from "vue";
  import { useRouter } from "vue-router";

  import ImposterBox from "./ImposterBox.vue";

  const { isToggled, toggleDialog } = defineProps<{
    /** Est-ce que la modale est activée ou non. */
    isToggled: boolean;
    /** Fonction déclenchant l'activation ou désactivation de la modale. */
    toggleDialog: () => void;
  }>();
  defineEmits<(e: "dialog-hidden", dialogId: string) => void>();

  const form = useTemplateRef<HTMLFormElement>("form");
  const router = useRouter();

  const resetAndClose = () => {
    form.value?.reset();
    toggleDialog();
  };

  const redirectToSearch = async (event: Event): void => {
    if (!form.value?.checkValidity()) return;
    event.preventDefault();

    await pipe(
      Effect.fromNullable(form.value),
      Effect.andThen((form: HTMLFormElement) => new FormData(form)),
      Effect.andThen((formData: FormData) => new URLSearchParams(formData)),
      Effect.andThen((searchParams: URLSearchParams) => Object.fromEntries(searchParams.entries())),
      Effect.tap(query => router.push({ path: "/search", query })),
      Effect.runPromise,
    );
  };
</script>

<template>
  <ImposterBox dialog-id="add-media" :is-toggled="isToggled" @dialog-hidden="resetAndClose">
    <template #title>Ajouter un média</template>
    <template #content>
      <form
        id="add-media-form" ref="form" action=""
        class="stack" method="dialog"
      >
        <fieldset class="cluster">
          <legend>Type du média</legend>
          <div class="field">
            <input
              id="film" checked for="add-media-form"
              name="type" type="radio" value="film"
            >
            <label for="film">Film</label>
          </div>

          <div class="field">
            <input
              id="series" for="add-media-form" name="type"
              type="radio" value="series"
            >
            <label for="series">Série</label>
          </div>
        </fieldset>

        <div class="field stack">
          <label for="query">Titre</label>
          <input
            id="query" for="add-media-form" name="query"
            required type="text"
          >
        </div>
        <div class="field stack">
          <label for="year">Année de sortie</label>
          <input
            id="year" for="add-media-form" name="year"
            type="number"
          >
        </div>

        <div class="cluster buttons">
          <button class="invert" type="submit" @click="redirectToSearch">
            Rechercher
          </button>
          <button type="reset">
            Réinitialiser
          </button>
        </div>
      </form>
    </template>
  </ImposterBox>
</template>
