<template>
  <div v-bind="$attrs">
    <q-input
      ref="inputRef"
      v-model="treatedDate"
      clearable
      :dense
      :error
      :error-message
      :label
      :mask="inputMask"
      :rules
    >
      <template #append>
        <q-icon
          class="cursor-pointer"
          :name="time ? 'mdi-calendar-clock' : 'mdi-calendar'"
        >
          <q-popup-proxy
            cover
            transition-hide="scale"
            transition-show="scale"
          >
            <template v-if="!time">
              <q-date
                v-model="date"
                color="primary"
                mask="YYYY-MM-DD"
                :class="['bg-surface', 'text-text', 'calendar-custom', calendarClass]"
              >
                <div class="row items-center justify-end">
                  <q-btn
                    v-close-popup
                    color="primary"
                    flat
                    label="Close"
                  />
                </div>
              </q-date>
            </template>

            <template v-else>
              <q-tab-panels
                v-model="activePanel"
                animated
                class="bg-white"
                transition-next="slide-left"
                transition-prev="slide-right"
              >
                <q-tab-panel
                  class="q-pa-none"
                  name="date"
                >
                  <q-date
                    v-model="date"
                    mask="YYYY-MM-DD HH:mm"
                    @update:model-value="handleDateSelection"
                  />
                </q-tab-panel>

                <q-tab-panel
                  class="q-pa-none"
                  name="time"
                >
                  <q-time
                    v-model="date"
                    format24h
                    mask="YYYY-MM-DD HH:mm"
                  />
                </q-tab-panel>
              </q-tab-panels>
            </template>
          </q-popup-proxy>
        </q-icon>
      </template>
    </q-input>
  </div>
</template>

<script setup>
import { computed, ref, useTemplateRef, watch } from "vue";
import { useI18n } from "vue-i18n";
import masks from "src/helpers/masks";

const treatedDate = defineModel();
const untreatedDate = defineModel("untreatedDate");

const { label, rules, time, dense, calendarClass } = defineProps({
  calendarClass: {
    type: String,
    default: "",
  },
  dense: {
    type: Boolean,
    default: false,
  },
  error: {
    type: Boolean,
    default: false,
  },
  errorMessage: {
    type: String,
    default: "",
  },
  label: {
    type: String,
    default: () => useI18n().t("common.terms.date"),
  },
  rules: {
    type: Array,
    default: () => [],
  },
  time: {
    type: Boolean,
    default: false,
  },
});

const qInputRef = useTemplateRef("inputRef");

const activePanel = ref("date");
const date = ref();

const inputMask = computed(() => {
  if (!qInputRef.value) return "";

  if (time) {
    return masks.Brasil.datetime;
  }
  return masks.Brasil.date;
});

const formatDate = (value) => {
  if (!value) return null;

  const [datePart, timePart] = value.split(" ");

  const formattedDate = datePart.split("-").reverse().join("/");

  return time && timePart ? `${formattedDate} ${timePart}` : formattedDate;
};

const handleDateSelection = () => {
  if (time) {
    activePanel.value = "time";
  }
};

const unformatDate = (value) => {
  if (!value) return null;

  const [datePart, timePart] = value.split(" ");

  const formattedDate = datePart.split("/").reverse().join("-");

  return time && timePart ? `${formattedDate} ${timePart}` : formattedDate;
};

watch(date, (value) => {
  if (!value) return;

  untreatedDate.value = value;

  treatedDate.value = formatDate(value);
});

watch(treatedDate, (value) => {
  if (!value) {
    date.value = null;
    untreatedDate.value = null;
    treatedDate.value = null;
    activePanel.value = "date";

    return;
  }

  date.value = unformatDate(value);
});

watch(
  untreatedDate,
  (value) => {
    if (!value) {
      date.value = null;
      untreatedDate.value = null;
      treatedDate.value = null;
      activePanel.value = "date";

      return;
    }

    date.value = value;

    treatedDate.value = formatDate(value);
  },
  { immediate: true },
);
</script>

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