<template>
  <SVGRect
    style="cursor: text"
    :rectangle="model.position"
    :variant="editing ? 'success' : 'primary'"
    @click.left.stop="on_click"
    visible
  >
    <input
      v-if="editing"
      v-model="day_str"
      ref="day_input"
      class="input is-large"
      type="number"
      :min="Door.MIN_DAY"
      placeholder="Tag"
      @keydown="on_keydown"
    />
    <div v-else class="has-text-danger">
      {{ model.day > 0 ? model.day : "*" }}
    </div>
  </SVGRect>
</template>

<script setup lang="ts">
import { Door } from "@/lib/rects/door";
import { ref, useTemplateRef } from "vue";

import { type VueLike, unwrap_vuelike, wait_for } from "@/lib/helpers";
import SVGRect from "../calendar/SVGRect.vue";

const model = defineModel<VueLike<Door>>({ required: true });
const day_input = useTemplateRef("day_input");

const day_str = ref("");
const editing = ref(false);

function toggle_editing(): void {
  day_str.value = String(model.value.day);
  editing.value = !editing.value;
}

function on_click(event: MouseEvent): void {
  if (!(event.target instanceof HTMLDivElement)) return;

  if (editing.value) {
    unwrap_vuelike(model.value).day = day_str.value;
  } else {
    wait_for(
      () => day_input.value !== null,
      () => day_input.value!.select(),
    );
  }

  toggle_editing();
}

function on_keydown(event: KeyboardEvent): void {
  if (!editing.value) return;

  if (event.key === "Enter") {
    unwrap_vuelike(model.value).day = day_str.value;
    toggle_editing();
  } else if (event.key === "Delete") {
    model.value.day = -1;
    toggle_editing();
  } else if (event.key === "Escape") {
    toggle_editing();
  }
}
</script>
