<template>
  <main class="d-flex align-center data-timing-range">
    <div v-if="show" class="d-flex align-center" style="max-height: 100%">
      <span class="pl-2 mr-2 font-weight-bold on-neutral" style="min-width: 150px;">
        {{ $t('period_choose') }}
      </span>

      <UiInputDateRangePicker
          :model-value="datesRange"
          :max-height="28"
          @update:model-value="updateDateTimeRange"
      />
    </div>

    <v-btn
        ref="btn"
        class="time-btn ml-1 theme-neutral-soft"
        height="22" min-height="22" max-height="22"
        width="25" min-width="25" max-width="25"
        elevation="0"
        @click="show = !show"
    >
      <v-icon icon="fas fa-history" class="font-weight-normal" style="font-size: 14px;" />
    </v-btn>

    <v-tooltip location="bottom" :activator="btn">
      <span>{{ $t('history_help') }}</span>
    </v-tooltip>
  </main>
</template>

<script setup lang="ts">
import {Ref} from "@vue/reactivity";
import {useAccessProfileStore} from "~/stores/accessProfile";
import {useFormStore} from "~/stores/form";
import {WatchStopHandle} from "@vue/runtime-core";
import {useEntityManager} from "~/composables/data/useEntityManager";
import Access from "~/models/Access/Access";
import DateUtils from "~/services/utils/dateUtils";

const btn: Ref = ref(null)
const show: Ref<boolean> = ref(false)

const { setDirty } = useFormStore()
const accessProfileStore = useAccessProfileStore()
const { em } = useEntityManager()

const start = accessProfileStore.historical.dateStart
const end = accessProfileStore.historical.dateStart

const datesRange: Ref<Array<Date> | null> = ref((start && end) ? [new Date(start), new Date(end)] : null)

const updateDateTimeRange = async (dates: Array<Date>): Promise<any> => {
  if (accessProfileStore.id === null) {
    throw new Error('Invalid profile id')
  }

  datesRange.value = dates

  if (datesRange.value === null || datesRange.value[0] === null || datesRange.value[1] === null) {
    return
  }

  accessProfileStore.setHistoricalRange(
      DateUtils.formatIsoShortDate(datesRange.value[0]),
      DateUtils.formatIsoShortDate(datesRange.value[1])
  )
  setDirty(false)

  console.log(accessProfileStore.id)
  console.log({'historical': accessProfileStore.historical})

  await em.patch(
      Access,
      accessProfileStore.id,
      {'historical': accessProfileStore.historical}
  )

  window.location.reload()
}

/**
 * Emit event when component is hidden / shown
  */
const emit = defineEmits(['showDateTimeRange'])

const unwatch: WatchStopHandle = watch(show, (newValue) => {
  emit('showDateTimeRange', newValue)
})

onUnmounted(() => {
  unwatch()
})

// Show by default if a date range is defined in store
if (accessProfileStore.historical.dateStart || accessProfileStore.historical.dateEnd) {
  show.value = true
  emit('showDateTimeRange', true)
}
</script>

<style scoped lang="scss">
.time-btn {
  border-width: 1px 1px 1px 0;
  border-style: solid;
}
</style>
