<script setup lang="ts">
import { ref, watch } from "vue";

import DialogHeader from "@/components/DialogHeader.vue";

import { useCounterMixin } from "@/stores/mixin";

const { date2Thai, dateToISO } = useCounterMixin();

const modal = defineModel<boolean>("modal", { required: true });
const title = defineModel<string>("title", { required: true });

const props = defineProps({
  onSubmit: { type: Function, require: true },
});

const date = ref<Date>(new Date()); // วันที่บัญชีใช้ได้ตั้งแต่

/** ฟังก์ชันบันทึกข้อมูลวันที่ */
function onSubmit() {
  if (!date.value) return;
  const dateISO = dateToISO(date.value);
  props.onSubmit?.(dateISO);
}

/** ฟังก์ชันปิดโมดัล */
function closeModal() {
  modal.value = false;
}

/** watch modal รีเซ็ตวันที่ */
watch(modal, (value) => {
  if (value) date.value = new Date();
});
</script>

<template>
  <q-dialog v-model="modal" persistent class="q-pt-none">
    <q-card style="min-width: 450px">
      <q-form @submit.prevent="onSubmit">
        <DialogHeader :tittle="title" :close="closeModal" />
        <q-separator />
        <q-card-section>
          <div class="col-12">
            <datepicker
              menu-class-name="modalfix"
              v-model="date"
              :locale="'th'"
              autoApply
              borderless
              :enableTimePicker="false"
              week-start="0"
            >
              <template #year="{ year }">
                {{ year + 543 }}
              </template>
              <template #year-overlay-value="{ value }">
                {{ parseInt(value + 543) }}
              </template>
              <template #trigger>
                <q-input
                  ref="dateRef"
                  outlined
                  dense
                  hide-bottom-space
                  :model-value="date != null ? date2Thai(date) : null"
                  label="วันที่บัญชีใช้ได้ตั้งแต่"
                >
                  <template v-slot:prepend>
                    <q-icon
                      name="event"
                      class="cursor-pointer"
                      style="color: var(--q-primary)"
                    >
                    </q-icon>
                  </template>
                </q-input>
              </template>
            </datepicker>
          </div>
        </q-card-section>
        <q-separator />
        <q-card-actions align="right">
          <q-btn color="public" label="บันทึก" type="submit" />
        </q-card-actions>
      </q-form>
    </q-card>
  </q-dialog>
</template>

<style lang="scss" scoped></style>
