<template>
  <DialogFrame ref="dialog" :header-title="'Edit ' + localTitle">
    <div class="row justify-center">
      <q-input autofocus :label="localTitle" filled v-model="value" @keyup.enter="save">
        <template
          v-if="['firstVisit', 'lastVisit', 'date', 'expiration'].includes(localField)"
          v-slot:prepend
        >
          <q-icon name="event" class="cursor-pointer">
            <q-popup-proxy cover transition-show="scale" transition-hide="scale">
              <q-date v-model="value" mask="YYYY-MM-DD HH:mm:ss">
                <div class="row items-center justify-end">
                  <q-btn :label="$t('now')" color="primary" no-caps flat @click="setTimeNow" />
                  <q-btn
                    v-if="localField"
                    :label="$t('never')"
                    color="primary"
                    no-caps
                    flat
                    @click="value = 'never'"
                  />
                  <q-btn no-caps v-close-popup :label="$t('close')" color="primary" flat />
                </div>
              </q-date>
            </q-popup-proxy>
          </q-icon>
        </template>
        <template
          v-if="['firstVisit', 'lastVisit', 'date', 'expiration'].includes(localField)"
          v-slot:append
        >
          <q-icon name="access_time" class="cursor-pointer">
            <q-popup-proxy cover transition-show="scale" transition-hide="scale">
              <q-time with-seconds v-model="value" mask="YYYY-MM-DD HH:mm:ss" format24h>
                <div class="row items-center justify-end">
                  <q-btn :label="$t('now')" color="primary" no-caps flat @click="setTimeNow" />
                  <q-btn
                    v-if="localField"
                    :label="$t('never')"
                    color="primary"
                    no-caps
                    flat
                    @click="value = 'never'"
                  />
                  <q-btn no-caps v-close-popup :label="$t('close')" color="primary" flat />
                </div>
              </q-time>
            </q-popup-proxy>
          </q-icon>
        </template>
      </q-input>
    </div>
    <div class="row justify-center">
      <q-btn class="q-ma-md" color="primary" no-caps @click="save">{{ $t('save') }}</q-btn>
    </div>
  </DialogFrame>
</template>

<script setup lang="ts">
import DialogFrame from 'src/vueLib/dialog/DialogFrame.vue';
import { ref } from 'vue';
import { appApi } from 'src/boot/axios';
import type { Member } from 'src/vueLib/models/member';
import { useNotify } from 'src/vueLib/general/useNotify';

const dialog = ref();
const localMember = ref();
const localTitle = ref('');
const localField = ref('');
const value = ref('');

const props = defineProps({
  endpoint: {
    type: String,
  },
});

const emit = defineEmits(['update']);
const { NotifyResponse } = useNotify();

function open(label: string, field: string, member: Member) {
  localTitle.value = label;
  localField.value = field;
  localMember.value = member;

  value.value = localMember.value[field];
  dialog.value?.open();
}

function save() {
  let payload = {};

  if (value.value === localMember.value[localField.value]) {
    dialog.value.close();
    return;
  }

  if (!props.endpoint) {
    localMember.value[localField.value] = value.value;
    emit('update', localMember.value);
    return;
  }
  payload = [
    {
      id: localMember.value.id,
      [localField.value]: value.value,
    },
  ];

  appApi
    .post(props.endpoint, payload)
    .then(() => {
      emit('update');
      dialog.value.close();
    })
    .catch((err) => {
      NotifyResponse(err, 'error');
    });
}

function setTimeNow() {
  const now = new Date();

  const year = now.getFullYear();
  const month = String(now.getMonth() + 1).padStart(2, '0'); // Months are 0-based
  const day = String(now.getDate()).padStart(2, '0');
  const hours = String(now.getHours()).padStart(2, '0');
  const minutes = String(now.getMinutes()).padStart(2, '0');
  const seconds = String(now.getSeconds()).padStart(2, '0');

  value.value = `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
}

defineExpose({ open });
</script>
