<template>
  <main class="d-flex align-baseline">
    <div v-if="show" class="d-flex align-baseline">
      <span class="mr-2 ot_dark_grey--text font-weight-bold">{{ $t('period_choose') }}</span>
      <UiInputDatePicker
        class="time-range"
        label="date_choose"
        :data="datesRange"
        :range="true"
        :dense="true"
        :single-line="true"
        @update="updateDateTimeRange"
      />
    </div>

    <v-tooltip bottom>
      <template #activator="{ on, attrs }">
        <v-btn
          class="time-btn"
          max-height="25"
          v-bind="attrs"
          elevation="0"
          max-width="10px"
          min-width="10px"
          v-on="on"
          @click="show=!show"
        >
          <v-icon color="ot_grey" class="font-weight-normal" x-small>
            fas fa-history
          </v-icon>
        </v-btn>
      </template>
      <span>{{ $t('history_help') }}</span>
    </v-tooltip>
  </main>
</template>

<script lang="ts">
import {
  defineComponent, onUnmounted, ref, watch, computed, ComputedRef, Ref, WatchStopHandle, useContext
} from '@nuxtjs/composition-api'
import { useMyProfile } from '~/composables/data/useMyProfile'
import {useForm} from "~/composables/form/useForm";

export default defineComponent({
  setup (_, { emit }) {
    const { store, $dataPersister } = useContext()
    const { markAsNotDirty } = useForm(store)
    const { updateMyProfile, setHistoricalRange, historical } = useMyProfile($dataPersister, store)

    const datesRange:ComputedRef<Array<any>> = computed(() => {
      return [historical.value.dateStart, historical.value.dateEnd]
    })

    const show:Ref<boolean> = ref(false)
    if (historical.value.dateStart || historical.value.dateEnd) {
      show.value = true
      emit('showDateTimeRange', true)
    }

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

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

    const updateDateTimeRange = async (dates:Array<string>): Promise<any> => {
      setHistoricalRange(dates)
      markAsNotDirty()
      await updateMyProfile()
      window.location.reload()
    }

    return {
      show,
      datesRange,
      updateDateTimeRange
    }
  }
})
</script>

<style lang="scss">
  .v-btn--active .v-icon{
    color: #FFF !important;
  }
  .time-btn{
    border-width: 1px 1px 1px 0px;
    border-style: solid;
    border-color: rgba(0, 0, 0, 0.12) !important;
  }
  .time-range{
    max-height: 20px;
    .v-text-field{
      padding-top: 0 !important;
      margin-top: 0 !important;
    }
    .v-icon{
      font-size: 20px;
    }
    input{
      font-size: 14px;
      width: 400px !important;
    }
  }
</style>
