<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 class="flex flex-row">
            <div
              v-for="tab in tabs"
              :key="tab.key"
              class="w-1/2 p-0.5 first:pl-0 last:pr-0"
              @click="
                active = tab.key;
                selectedType = '';
              "
            >
              <p
                :class="[
                  'w-full rounded-lg py-2.5 text-sm text-center font-medium leading-5 focus:ring-0 outline-hidden',
                  tab.key == active
                    ? 'bg-red-200 shadow-sm border-b-2 border-primary rounded-b-none'
                    : ' hover:bg-red-200',
                ]"
              >
                {{ tab.title }}
              </p>
            </div>
          </div>

          <EquipmentTypeSearchSelect v-if="active == 'gear'" title="Typ" v-model="selectedType" />
          <VehicleTypeSearchSelect v-else title="Typ" v-model="selectedType" />

          <div>
            <label for="name">Bezeichnung</label>
            <input type="text" id="name" required />
          </div>
          <div>
            <label for="interval">Intervall</label>
            <input
              type="text"
              id="interval"
              placeholder="<zahl>-(d|m|y) oder DD/MM oder DD/*"
              required
              pattern="^\d+-(d|m|y)$|^\d{2}/\d{2}$|^\d{2}/\*$"
              title="Eingabe muss im Format <zahl>-(d|m|y), DD/MM oder DD/* sein"
            />
          </div>
          <div>
            <label for="remind">Erinnerung vor Fälligkeit</label>
            <input
              type="text"
              id="remind"
              placeholder="<zahl>-(d|m|y) oder DD/MM oder DD/*"
              required
              pattern="^\d+-(d|m|y)$|^\d{2}/\d{2}$|^\d{2}/\*$"
              title="Eingabe muss im Format <zahl>-(d|m|y), DD/MM oder DD/* sein"
            />
          </div>
          <div class="flex flex-row justify-end gap-2">
            <RouterLink
              :to="{ name: 'admin-unit-inspection_plan' }"
              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";
import EquipmentTypeSearchSelect from "@/components/search/EquipmentTypeSearchSelect.vue";
import VehicleTypeSearchSelect from "@/components/search/VehicleTypeSearchSelect.vue";
</script>

<script lang="ts">
export default defineComponent({
  data() {
    return {
      status: null as null | "loading" | { status: "success" | "failed"; reason?: string },
      timeout: null as any,
      selectedType: "" as string,
      active: "gear" as string,
      tabs: [
        {
          key: "gear",
          title: "Gerät",
        },
        {
          key: "vehicle",
          title: "Fahrzeug",
        },
      ],
    };
  },
  computed: {
    ...mapState(useInspectionPlanStore, ["inspectionPlans"]),
  },
  beforeUnmount() {
    try {
      clearTimeout(this.timeout);
    } catch (error) {}
  },
  methods: {
    ...mapActions(useInspectionPlanStore, ["createInspectionPlan"]),
    ...mapActions(useEquipmentTypeStore, ["searchEquipmentTypes"]),
    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,
        remindTime: formData.name.value,
      };
      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>
