<template>
  <SVGRect
    style="cursor: text"
    :rectangle="model.position"
    :variant="editing ? 'success' : 'primary'"
    @click.left="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 { nextTick, ref, useTemplateRef } from "vue";

import SVGRect from "../calendar/SVGRect.vue";

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

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

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

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

  if (!editing.value) {
    const day_input_focus = () => {
      if (day_input.value === null) {
        nextTick(day_input_focus);
        return;
      }

      day_input.value.select();
    };
    day_input_focus();
  } else {
    model.value.day = day_str.value;
  }

  toggle_editing();
}

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

  if (event.key === "Enter") {
    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>
