<template>
  <MainTemplate>
    <template #topBar>
      <div class="flex flex-row items-center justify-between pt-5 pb-3 px-7">
        <h1 class="font-bold text-xl h-8">Ausrüstung erfassen</h1>
      </div>
    </template>
    <template #diffMain>
      <div class="flex flex-col gap-2 h-full w-full overflow-y-auto">
        <form class="flex flex-col gap-4 py-2 w-full max-w-xl mx-auto" @submit.prevent="triggerCreate">
          <div>
            <Combobox v-model="selectedType">
              <ComboboxLabel>Typ</ComboboxLabel>
              <div class="relative mt-1">
                <ComboboxInput
                  class="rounded-md shadow-xs relative block w-full px-3 py-2 border border-gray-300 focus:border-primary placeholder-gray-500 text-gray-900 rounded-b-md focus:outline-hidden focus:ring-0 focus:z-10 sm:text-sm resize-none"
                  @input="query = $event.target.value"
                />
                <ComboboxButton class="absolute inset-y-0 right-0 flex items-center pr-2">
                  <ChevronUpDownIcon class="h-5 w-5 text-gray-400" aria-hidden="true" />
                </ComboboxButton>
                <TransitionRoot
                  leave="transition ease-in duration-100"
                  leaveFrom="opacity-100"
                  leaveTo="opacity-0"
                  @after-leave="query = ''"
                >
                  <ComboboxOptions
                    class="z-20 absolute mt-1 max-h-60 w-full overflow-auto rounded-md bg-white py-1 text-base shadow-md ring-1 ring-black/5 focus:outline-hidden sm:text-sm"
                  >
                    <ComboboxOption v-if="loading || deferingSearch" as="template" disabled>
                      <li class="flex flex-row gap-2 text-text relative cursor-default select-none py-2 pl-3 pr-4">
                        <Spinner />
                        <span class="font-normal block truncate">suche</span>
                      </li>
                    </ComboboxOption>
                    <ComboboxOption v-else-if="filtered.length === 0 && query == ''" as="template" disabled>
                      <li class="text-text relative cursor-default select-none py-2 pl-3 pr-4">
                        <span class="font-normal block truncate">tippe, um zu suchen...</span>
                      </li>
                    </ComboboxOption>
                    <ComboboxOption v-else-if="filtered.length === 0" as="template" disabled>
                      <li class="text-text relative cursor-default select-none py-2 pl-3 pr-4">
                        <span class="font-normal block truncate">Keine Auswahl gefunden.</span>
                      </li>
                    </ComboboxOption>

                    <ComboboxOption
                      v-if="!(loading || deferingSearch)"
                      v-for="type in filtered"
                      as="template"
                      :key="type.id"
                      :value="type.id"
                      v-slot="{ selected, active }"
                    >
                      <li
                        class="relative cursor-default select-none py-2 pl-10 pr-4"
                        :class="{
                          'bg-primary text-white': active,
                          'text-gray-900': !active,
                        }"
                      >
                        <span class="block truncate" :class="{ 'font-medium': selected, 'font-normal': !selected }">
                          {{ type.type }}
                        </span>
                        <span
                          v-if="selected"
                          class="absolute inset-y-0 left-0 flex items-center pl-3"
                          :class="{ 'text-white': active, 'text-primary': !active }"
                        >
                          <CheckIcon class="h-5 w-5" aria-hidden="true" />
                        </span>
                      </li>
                    </ComboboxOption>
                  </ComboboxOptions>
                </TransitionRoot>
              </div>
            </Combobox>
          </div>
          <div>
            <label for="name">Bezeichnung</label>
            <input type="text" id="name" required />
          </div>
          <div>
            <label for="interval">Intervall (optional)</label>
            <input type="text" id="interval" placeholder="<number>-(d|m|y) oder DD/MM" />
          </div>
          <div class="flex flex-row justify-end gap-2">
            <RouterLink
              :to="{ name: 'admin-unit-inspectionPlan' }"
              primary-outline
              button
              class="w-fit!"
              :disabled="status == 'loading' || status?.status == 'success'"
            >
              abbrechen
            </RouterLink>
            <button primary type="submit" class="w-fit!" :disabled="status == 'loading'">speichern</button>
            <Spinner v-if="status == 'loading'" class="my-auto" />
            <SuccessCheckmark v-else-if="status?.status == 'success'" />
            <FailureXMark v-else-if="status?.status == 'failed'" />
          </div>
        </form>
      </div>
    </template>
  </MainTemplate>
</template>

<script setup lang="ts">
import { defineComponent } from "vue";
import { mapActions, mapState } from "pinia";
import MainTemplate from "@/templates/Main.vue";
import Spinner from "@/components/Spinner.vue";
import SuccessCheckmark from "@/components/SuccessCheckmark.vue";
import FailureXMark from "@/components/FailureXMark.vue";
import {
  Combobox,
  ComboboxLabel,
  ComboboxInput,
  ComboboxButton,
  ComboboxOptions,
  ComboboxOption,
  TransitionRoot,
} from "@headlessui/vue";
import { CheckIcon, ChevronUpDownIcon } from "@heroicons/vue/20/solid";
import { useInspectionPlanStore } from "@/stores/admin/unit/inspectionPlan/inspectionPlan";
import type { CreateInspectionPlanViewModel } from "@/viewmodels/admin/unit/inspectionPlan/inspectionPlan.models";
import ScanInput from "@/components/ScanInput.vue";
import type { EquipmentTypeViewModel } from "../../../../viewmodels/admin/unit/equipmentType/equipmentType.models";
import { useEquipmentTypeStore } from "../../../../stores/admin/unit/equipmentType/equipmentType";
</script>

<script lang="ts">
export default defineComponent({
  watch: {
    query() {
      this.deferingSearch = true;
      clearTimeout(this.timer);
      this.timer = setTimeout(() => {
        this.deferingSearch = false;
        this.search();
      }, 600);
    },
  },
  data() {
    return {
      status: null as null | "loading" | { status: "success" | "failed"; reason?: string },
      timeout: null as any,
      selectedType: null as null | string,
      loading: false as boolean,
      deferingSearch: false as boolean,
      timer: undefined as any,
      query: "" as string,
      filtered: [] as Array<EquipmentTypeViewModel>,
    };
  },
  computed: {
    ...mapState(useInspectionPlanStore, ["inspectionPlans"]),
  },
  beforeUnmount() {
    try {
      clearTimeout(this.timeout);
    } catch (error) {}
  },
  methods: {
    ...mapActions(useInspectionPlanStore, ["createInspectionPlan"]),
    ...mapActions(useEquipmentTypeStore, ["searchEquipmentTypes"]),
    search() {
      this.filtered = [];
      if (this.query == "") return;
      this.loading = true;
      this.searchEquipmentTypes(this.query)
        .then((res) => {
          this.filtered = res.data;
        })
        .catch((err) => {})
        .finally(() => {
          this.loading = false;
        });
    },
    triggerCreate(e: any) {
      if (this.selectedType == null) return;
      let formData = e.target.elements;
      let createInspectionPlan: CreateInspectionPlanViewModel = {
        title: formData.name.value,
        equipmentTypeId: "",
        inspectionInterval: formData.name.value || null,
      };
      this.status = "loading";
      this.createInspectionPlan(createInspectionPlan)
        .then((res) => {
          this.status = { status: "success" };

          this.timeout = setTimeout(() => {
            this.$router.push({
              name: "admin-unit-inspectionPlan-overview",
              params: {
                inspectionPlanId: res.data,
              },
            });
          }, 1500);
        })
        .catch((err) => {
          this.status = { status: "failed" };
        });
    },
  },
});
</script>
