<template>
  <BulmaDrawer header="Türchen bearbeiten" :opening="load_doors">
    <nav class="level is-mobile mb-0" style="overflow-x: auto">
      <BulmaButton
        :disabled="current_step === 0"
        class="level-item is-link"
        @click="current_step--"
        :icon="['fas', 'fa-backward']"
      />

      <BulmaBreadcrumbs
        :steps="steps"
        v-model="current_step"
        class="level-item mb-0"
      />

      <BulmaButton
        :disabled="current_step === 2"
        class="level-item is-link"
        @click="current_step++"
        :icon="['fas', 'fa-forward']"
      />
    </nav>

    <div class="card-content pb-0">
      <div v-if="doors.length > 0" class="content">
        <p>Für diese Tage ist ein Türchen vorhanden:</p>
        <div class="tags">
          <span
            v-for="(door, index) in doors.toSorted((a, b) => a.day - b.day)"
            :key="`door-${index}`"
            class="tag is-primary"
          >
            {{ door.day }}
          </span>
        </div>
      </div>
    </div>

    <DoorPlacer v-if="current_step === 0" v-model="doors" />
    <DoorChooser v-if="current_step === 1" v-model="doors" />
    <div v-if="current_step === 2" class="card-content">
      <Calendar :doors="doors" />
    </div>

    <footer class="card-footer is-flex is-justify-content-space-around">
      <BulmaButton
        class="card-footer-item is-danger"
        @click="on_download"
        :icon="['fas', 'fa-cloud-arrow-down']"
        :busy="loading_doors"
        text="Laden"
      />
      <BulmaButton
        class="card-footer-item is-warning"
        @click="on_discard"
        :icon="['fas', 'fa-trash']"
        text="Löschen"
      />
      <BulmaButton
        class="card-footer-item is-success"
        @click="on_upload"
        :icon="['fas', 'fa-cloud-arrow-up']"
        :busy="saving_doors"
        text="Speichern"
      />
    </footer>
  </BulmaDrawer>
</template>

<script setup lang="ts">
import { API } from "@/lib/api";
import { APIError } from "@/lib/api_error";
import type { DoorSaved } from "@/lib/model";
import { Door } from "@/lib/rects/door";
import { toast } from "bulma-toast";
import { ref } from "vue";
import type { BCStep } from "../bulma/Breadcrumbs.vue";

import Calendar from "../Calendar.vue";
import BulmaBreadcrumbs from "../bulma/Breadcrumbs.vue";
import BulmaButton from "../bulma/Button.vue";
import BulmaDrawer from "../bulma/Drawer.vue";
import DoorChooser from "../editor/DoorChooser.vue";
import DoorPlacer from "../editor/DoorPlacer.vue";

const steps: BCStep[] = [
  { label: "Platzieren", icon: ["fas", "fa-crosshairs"] },
  { label: "Ordnen", icon: ["fas", "fa-list-ol"] },
  { label: "Vorschau", icon: ["fas", "fa-magnifying-glass"] },
];

const doors = ref<Door[]>([]);
const current_step = ref(0);
const loading_doors = ref(false);
const saving_doors = ref(false);

async function load_doors(): Promise<void> {
  try {
    const data = await API.request<DoorSaved[]>("admin/doors");

    doors.value.length = 0;
    for (const value of data) {
      doors.value.push(Door.load(value));
    }
  } catch (error) {
    APIError.alert(error);
    throw null;
  }
}

async function save_doors(): Promise<void> {
  try {
    const data: DoorSaved[] = [];

    for (const door of doors.value) {
      data.push(door.save());
    }

    await API.request<void>({
      endpoint: "admin/doors",
      method: "PUT",
      data: data,
    });
  } catch (error) {
    APIError.alert(error);
    throw null;
  }
}

async function on_download(): Promise<void> {
  if (confirm("Aktuelle Änderungen verwerfen und Status vom Server laden?")) {
    loading_doors.value = true;

    try {
      load_doors();

      toast({
        message: "Erfolgreich!",
        type: "is-success",
        duration: 2e3,
      });
    } finally {
      loading_doors.value = false;
    }
  }
}

function on_discard(): void {
  if (confirm("Alle Türchen löschen? (nur lokal)")) {
    // empty `doors` array
    doors.value.length = 0;
  }
}

async function on_upload(): Promise<void> {
  if (confirm("Aktuelle Änderungen an den Server schicken?")) {
    saving_doors.value = true;

    try {
      save_doors();
      load_doors();

      toast({
        message: "Erfolgreich!",
        type: "is-success",
        duration: 2e3,
      });
    } finally {
      saving_doors.value = false;
    }
  }
}
</script>
