<script setup lang="ts">
import { onMounted, ref } from 'vue'
import { useI18n } from 'vue-i18n'
import { RangType } from './type.d'

const emit = defineEmits<{
  updateSearchList: [currentTime: RangType, startTime: string, endTime: string]
}>()

const { t } = useI18n()

const currentTime = ref(RangType.week)

const selectDateRange = ref<[string, string]>(['', ''])

const rangTypeOptionList = [
  {
    label: t('common_module.last_week'),
    value: RangType.week,
  },
  {
    label: t('common_module.last_month'),
    value: RangType.month,
  },
  {
    label: t('common_module.custom'),
    value: RangType.customize,
  },
]

const disableSelectDate = (ts: number, type: 'start' | 'end', range: [number, number] | null) => {
  if (type === 'start' && range !== null) {
    return range[1] - ts >= 86400000 * 365 || ts > Date.now()
  }
  if (type === 'end' && range !== null) {
    return ts - range[0] >= 86400000 * 365 || ts > Date.now()
  }

  return ts > Date.now()
}

onMounted(() => {
  emit('updateSearchList', currentTime.value, '', '')
})

function handleUpdateRangType(rangType: string) {
  if (rangType !== RangType.customize) {
    selectDateRange.value = ['', '']
    emit('updateSearchList', currentTime.value, '', '')
  }
}

function handleUpdateDateRange(_value: [number, number], formattedValue: [string, string]) {
  if (formattedValue && formattedValue[0] && formattedValue[1]) {
    selectDateRange.value = formattedValue
    emit('updateSearchList', currentTime.value, selectDateRange.value[0], selectDateRange.value[1])
  }
}
</script>

<template>
  <div class="flex gap-3">
    <n-select
      v-model:value="currentTime"
      :options="rangTypeOptionList"
      class="w-[124px]! time-range-select"
      @update:value="handleUpdateRangType"
    />

    <n-date-picker
      v-show="currentTime === 'customize'"
      type="daterange"
      :is-date-disabled="disableSelectDate"
      clearable
      class="w-[250px]! customize-date-picker"
      @update:value="handleUpdateDateRange"
    />
  </div>
</template>

<style scoped lang="scss">
:deep(.time-range-select .n-base-selection),
:deep(.customize-date-picker.n-date-picker .n-input) {
  --n-height: 36px !important;
}
</style>
