<script setup lang="ts">
import { onMounted, onUnmounted } from 'vue'

const props = withDefaults(
  defineProps<{
    open: boolean
    mode: 'create' | 'edit'
    tree: 'ตู้เอกสาร' | 'ลิ้นชัก' | 'แฟ้ม' | 'แฟ้มย่อย'
    name?: string
  }>(),
  {
    open: false,
  }
)

const emit = defineEmits(['update:open', 'update:name', 'submit'])

function reset() {
  emit('update:name', undefined)
}

function keydown(e: KeyboardEvent) {
  if (e.key === 'Escape' && props.open === true) {
    emit('update:open', false)
    reset()
  }
}

function submit() {
  emit('submit', {
    mode: props.mode,
    name: props.name,
  })
  reset()
}

onMounted(() => window.addEventListener('keydown', keydown))
onUnmounted(() => window.addEventListener('keydown', keydown))
</script>

<template>
  <q-drawer
    overlay
    bordered
    class="q-pa-md"
    side="right"
    tabindex="0"
    :width="300"
    :breakpoint="500"
    :model-value="open"
  >
    <q-form @submit.prevent="submit">
      <q-toolbar class="q-mb-md q-pa-none">
        <q-toolbar-title>
          <span class="text-weight-bold" v-if="mode === 'create'">
            สร้าง{{ tree }}
          </span>
          <span class="text-weight-bold" v-if="mode === 'edit'">
            แก้ไข{{ tree }}
          </span>
        </q-toolbar-title>
        <q-btn
          v-close-popup
          flat
          round
          dense
          icon="close"
          color="red"
          @click="() => $emit('update:open', !open)"
        />
      </q-toolbar>

      <section class="q-mb-md">
        <span class="text-weight-bold">ชื่อ{{ tree }}</span>
        <q-input
          outlined
          dense
          class="q-my-sm"
          placeholder="กรอกชื่อ"
          :model-value="name"
          @update:model-value="(v) => $emit('update:name', v)"
        />
      </section>

      <section :style="{ display: 'flex', gap: '.5rem' }">
        <q-btn label="บันทึก" type="submit" color="primary" />
        <q-btn
          label="ยกเลิก"
          type="reset"
          color="primary"
          flat
          @click="() => ($emit('update:open', false), reset())"
        />
      </section>
    </q-form>
  </q-drawer>
</template>

<style scoped>
.no-resize >>> textarea {
  resize: none;
}
</style>
