<template>
  <div class="flex flex-col gap-2 h-full w-full overflow-y-auto">
    <Spinner v-if="loading == 'loading'" class="mx-auto" />
    <p v-else-if="loading == 'failed'">laden fehlgeschlagen</p>
    <form
      v-else-if="vehicle != null"
      class="flex flex-col gap-4 py-2 w-full max-w-xl mx-auto"
      @submit.prevent="triggerUpdate"
    >
      <p class="mx-auto">Fahrzeug bearbeiten</p>
      <div>
        <label for="name">Bezeichnung</label>
        <input type="text" id="name" required v-model="vehicle.name" />
      </div>
      <ScanInput name="code" label="Code" :required="false" />
      <div>
        <label for="location">Verortung (optional)</label>
        <input type="text" id="location" />
      </div>
      <div>
        <label for="commissioned">In-Betrieb-Nahme</label>
        <input type="date" id="commissioned" required v-model="vehicle.commissioned" />
      </div>
      <div>
        <label for="decommissioned">Außer-Betrieb-Nahme (optional)</label>
        <input type="date" id="decommissioned" v-model="vehicle.decommissioned" />
      </div>
      <div class="flex flex-row justify-end gap-2">
        <RouterLink
          :to="{ name: 'admin-unit-vehicle' }"
          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>

<script setup lang="ts">
import { defineComponent } from "vue";
import { mapActions, mapState } from "pinia";
import { useVehicleStore } from "@/stores/admin/unit/vehicle/vehicle";
import type { UpdateVehicleViewModel, VehicleViewModel } from "@/viewmodels/admin/unit/vehicle/vehicle.models";
import Spinner from "@/components/Spinner.vue";
import SuccessCheckmark from "@/components/SuccessCheckmark.vue";
import FailureXMark from "@/components/FailureXMark.vue";
import ScanInput from "@/components/scanner/ScanInput.vue";
import isEqual from "lodash.isequal";
import cloneDeep from "lodash.clonedeep";
</script>

<script lang="ts">
export default defineComponent({
  props: {
    vehicleId: String,
  },
  watch: {
    loadingActive() {
      if (this.loading == "loading") {
        this.loading = this.loadingActive;
      }
      if (this.loadingActive == "fetched") this.vehicle = cloneDeep(this.activeVehicleObj);
    },
  },
  data() {
    return {
      loading: "loading" as "loading" | "fetched" | "failed",
      status: null as null | "loading" | { status: "success" | "failed"; reason?: string },
      vehicle: null as null | VehicleViewModel,
      timeout: null as any,
    };
  },
  computed: {
    canSaveOrReset(): boolean {
      return isEqual(this.activeVehicleObj, this.vehicle);
    },
    ...mapState(useVehicleStore, ["activeVehicleObj", "loadingActive"]),
  },
  mounted() {
    this.fetchItem();
  },
  beforeUnmount() {
    try {
      clearTimeout(this.timeout);
    } catch (error) {}
  },
  methods: {
    ...mapActions(useVehicleStore, ["updateActiveVehicle", "fetchVehicleByActiveId"]),
    resetForm() {
      this.vehicle = cloneDeep(this.activeVehicleObj);
    },
    fetchItem() {
      this.fetchVehicleByActiveId();
    },
    triggerUpdate(e: any) {
      if (this.vehicle == null) return;
      let formData = e.target.elements;
      let updateVehicle: UpdateVehicleViewModel = {
        id: this.vehicle.id,
        name: formData.name.value,
        code: formData.code.value || null,
        location: formData.location.value,
        commissioned: formData.commissioned.value,
        decommissioned: formData.decommissioned.value ?? null,
      };
      this.status = "loading";
      this.updateActiveVehicle(updateVehicle)
        .then((res) => {
          this.status = { status: "success" };
        })
        .catch((err) => {
          this.status = { status: "failed" };
        })
        .finally(() => {
          this.timeout = setTimeout(() => {
            this.status = null;
          }, 2000);
        });
    },
  },
});
</script>
