<script setup lang="ts">
import { useOptions } from '@/composables/dateOpt'
import { cn } from '@/lib/utils'
import {
  DateFormatter,
  type DateValue,
  getLocalTimeZone,
  isSameDay,
  parseDate,
} from '@internationalized/date'

const df = new DateFormatter('en-US', {
  dateStyle: 'long',
})

const {
  options,
  castBeginDate,
  castTargetDate,
} = useOptions()

const mapping = ref < Record<string, string>>({})

onMounted(async () => {
  const resp = await baseFetch('/tc/metadata').json()
  const data = resp.data.value.data
  mapping.value = data
  options.mapping = data
  const date = Object.keys(data)[0]
  const newDateStr = `${date.slice(0, 4)}-${date.slice(4, 6)}-${date.slice(6, 8)}`

  if (castBeginDate.value === undefined) {
    castBeginDate.value = parseDate(newDateStr)
  }
  if (options.castDayNo === -1) {
    castTargetDate.value = castBeginDate.value.add({ days: 1 })
  }
})

const isDateDisabled = computed(() => {
  const availableDates = Object.keys(mapping.value)
    .map((date: string) => {
      // date is like 20020202, we need to first trans to 2002-02-02
      try {
        const newDateStr = `${date.slice(0, 4)}-${date.slice(4, 6)}-${date.slice(6, 8)}`
        const newDate = parseDate(newDateStr)
        return newDate
      }
      catch {
        return null
      }
    })
    .filter(date => date !== null) as DateValue[]
  function _isDateDisabled(date: DateValue): boolean {
    const hasMatch = availableDates.some((thisDate) => {
      return isSameDay(date, thisDate)
    })
    return !hasMatch
  }
  return _isDateDisabled
})

const isTargetDateDisabled = computed(() => {
  const castBegin = castBeginDate.value
  function _functionIsTargetDateDisabled(date: DateValue): boolean {
    if (!castBegin) {
      return true
    }
    const castEnd = castBegin.add({ days: 29 })
    return date.compare(castBegin) < 0 || date.compare(castEnd) > 0
  }
  return _functionIsTargetDateDisabled
})
</script>

<template>
  <form class="grid w-full items-start gap-6">
    <fieldset class="grid gap-6 border rounded-lg p-4">
      <legend class="px-1 text-sm font-medium -ml-1">
        <span class="i-material-symbols-settings size-5" />
      </legend>
      <div class="grid gap-3">
        <Label for="model">展示方式</Label>
        <Select v-model="options.renderMode">
          <SelectTrigger
            id="model"
            class="items-start [&_[data-description]]:hidden"
          >
            <SelectValue placeholder="Select a model" />
          </SelectTrigger>
          <SelectContent class="z-400">
            <SelectItem value="heatmap">
              <div class="flex items-start gap-3 text-muted-foreground">
                <span class="i-tabler-sun size-5" />
                <div class="grid gap-0.5">
                  <p>
                    热图
                    <span class="text-foreground font-medium">
                      使用点状热力图渲染
                    </span>
                  </p>
                  <p class="text-xs" data-description>
                    放大缩小可能不准确
                  </p>
                </div>
              </div>
            </SelectItem>
            <SelectItem value="image">
              <div class="flex items-start gap-3 text-muted-foreground">
                <span class="i-material-symbols-image size-5" />
                <div class="grid gap-0.5">
                  <p>
                    图片
                    <span class="text-foreground font-medium">
                      使用图片叠加层渲染
                    </span>
                  </p>
                  <p class="text-xs" data-description>
                    相对准确
                  </p>
                </div>
              </div>
            </SelectItem>
          </SelectContent>
        </Select>
      </div>
      <div class="grid grid-cols-2 gap-3">
        <div>
          <Label for="temperature">发布日期</Label>
          <Popover>
            <PopoverTrigger as-child>
              <Button
                variant="outline"
                :class="cn(
                  'w-full justify-start text-left font-normal',
                  !castBeginDate && 'text-muted-foreground',
                )"
              >
                <span class="i-uil-calender mr-2 h-4 w-4" />
                {{ castBeginDate ? df.format(castBeginDate.toDate(getLocalTimeZone())) : "Pick a date" }}
              </Button>
            </PopoverTrigger>
            <PopoverContent class="w-aut1o z-300 p-0">
              <Calendar
                v-model="castBeginDate" class="z-300"
                initial-focus :is-date-disabled="isDateDisabled"
                prevent-deselect
              />
            </PopoverContent>
          </Popover>
        </div>
        <div>
          <Label for="top-p">目标预报日期</Label>
          <Popover>
            <PopoverTrigger as-child>
              <Button
                variant="outline"
                :class="cn(
                  'w-full justify-start text-left font-normal',
                  !castTargetDate && 'text-muted-foreground',
                )"
              >
                <span class="i-uil-calender mr-2 h-4 w-4" />

                {{ castTargetDate ? df.format(castTargetDate.toDate(getLocalTimeZone())) : "Pick a date" }}
              </Button>
            </PopoverTrigger>
            <PopoverContent class="z-300 w-auto p-0">
              <Calendar
                v-model="castTargetDate"
                class="z-300" initial-focus
                :is-date-disabled="isTargetDateDisabled"
                prevent-deselect
              />
            </PopoverContent>
          </Popover>
        </div>
      </div>
      <div class="grid gap-3" />
    </fieldset>
  </form>
</template>

<style scoped>

</style>
