<template>
  <MultiModal @handle="on_modal_handle" />

  <BulmaDrawer header="Kalender-Assistent" :opening="on_open" refreshable>
    <div class="card-content">
      <div class="content">
        <p>Hervorgehobenen Tagen wurde kein Buchstabe zugewiesen.</p>

        <h3>Zuordnung Buchstaben</h3>
        <div class="tags are-medium">
          <template v-for="(data, day) in day_data" :key="`part-${day}`">
            <span v-if="data.part === ''" class="tag is-warning">
              {{ day }}
            </span>
            <span v-else class="tag is-info">
              {{ day }}: {{ data.part.split("").join(", ") }}
            </span>
          </template>
        </div>

        <h3>Zuordnung Bilder</h3>
        <div class="tags are-medium">
          <span
            v-for="(data, day) in day_data"
            :key="`image-${day}`"
            :class="'tag is-' + (data.part === '' ? 'warning' : 'primary')"
          >
            {{ day }}: {{ data.image_name }}
          </span>
        </div>

        <h3>Alle Türchen</h3>
        <div class="tags are-medium">
          <BulmaButton
            v-for="(data, day) in day_data"
            :key="`btn-${day}`"
            :class="'tag is-' + (data.part === '' ? 'warning' : 'info')"
            icon="fa-solid fa-door-open"
            :text="day.toString()"
            @click.left="door_click(Number(day))"
          />
        </div>
      </div>
    </div>
  </BulmaDrawer>
</template>

<script setup lang="ts">
import { API } from "@/lib/api";
import { name_door, objForEach } from "@/lib/helpers";
import { ImageData, NumStrDict } from "@/lib/model";
import { ref } from "vue";

import MultiModal, { HMultiModal } from "../MultiModal.vue";
import BulmaButton from "../bulma/Button.vue";
import BulmaDrawer from "../bulma/Drawer.vue";

const day_data = ref<Record<number, { part: string; image_name: string }>>({});

let modal: HMultiModal | undefined;

function on_modal_handle(handle: HMultiModal) {
  modal = handle;
}

async function on_open() {
  const [day_parts, day_image_names] = await Promise.all([
    API.request<NumStrDict>("admin/day_parts"),
    API.request<NumStrDict>("admin/day_image_names"),
  ]);

  const _ensure_day_in_data = (day: number) => {
    if (!(day in day_data.value)) {
      day_data.value[day] = { part: "", image_name: "" };
    }
  };

  objForEach(day_parts, (day, part) => {
    _ensure_day_in_data(day);
    day_data.value[day].part = part;
  });

  objForEach(day_image_names, (day, image_name) => {
    _ensure_day_in_data(day);
    day_data.value[day].image_name = image_name;
  });
}

async function door_click(day: number) {
  if (modal === undefined) return;
  modal.show_loading();

  try {
    const day_image = await API.request<ImageData>(`user/image_${day}`);
    modal.show_image(day_image.data_url, name_door(day));
  } catch {
    modal.hide();
  }
}
</script>
