<script setup lang="ts">
import { format } from 'date-fns'
import { computed } from 'vue'
import { useFdsI18n } from '../../plugin/useFdsI18n'
import FdsMeta from '../Typography/FdsMeta/FdsMeta.vue'

const props = withDefaults(
  defineProps<{
    date: Date
    disabled?: boolean
    selected?: boolean
    isToday?: boolean
  }>(),
  {
    disabled: false,
    selected: false,
    isToday: false,
  },
)

const emit = defineEmits<{
  (e: 'select-date', date: Date | null): void
}>()

const { locale, t } = useFdsI18n()

const classes = computed(() => [
  'box-border flex h-[64px] w-full max-w-[100px] flex-1 basis-0 flex-col items-center justify-center border-2 border-transparent px-1 py-1 transition-colors cursor-pointer',
  props.disabled ? '' : 'hover:border-2 hover:border-blue-500 border-solid',
  props.disabled ? '' : 'active:bg-blue_t-100 border-transparent',
  props.disabled ? '' : 'focus:outline-none',
  props.disabled ? '' : 'focus-visible:border-2 focus-visible:border-blue-500 focus-visible:outline-none border-dashed',
  props.selected ? 'bg-blue-600 border-transparent!' : 'bg-white-solid',
  props.disabled ? 'cursor-not-allowed text-blue-200!' : '',
])

const dayNumberClasses = computed(() => [
  'font-bold leading-6',
  props.selected ? 'text-white-solid' : props.disabled ? 'text-blue-200!' : 'text-blue-600',
])

const weekdayLabelClasses = computed(() => [
  props.selected ? 'text-white-solid' : props.disabled ? 'text-blue-200!' : 'text-gray-700',
])

const onClick = () => {
  if (props.disabled) return
  emit('select-date', props.selected ? null : props.date)
}

const weekdayLabel = computed(() => {
  const value = new Intl.DateTimeFormat(locale.value, { weekday: 'short' }).format(props.date)
  return value.charAt(0).toUpperCase() + value.slice(1).replace('.', '')
})

const dateAriaLabel = computed(() => {
  const spokenDate = new Intl.DateTimeFormat(locale.value, {
    day: 'numeric',
    month: 'long',
    weekday: 'long',
  }).format(props.date)

  const normalizedDate = spokenDate.charAt(0).toUpperCase() + spokenDate.slice(1)
  if (props.isToday) {
    return `${t('FdsWeekCalendar.today')}. ${normalizedDate}.`
  }

  return `${normalizedDate}.`
})
</script>

<template>
  <button type="button" :class="classes" :disabled="disabled" :aria-label="dateAriaLabel" @click="onClick">
    <span :class="dayNumberClasses">{{ format(date, 'd') }}</span>
    <span :class="weekdayLabelClasses">
      <FdsMeta v-if="isToday">{{ t('FdsWeekCalendar.today') }}</FdsMeta>
      <FdsMeta v-else>{{ weekdayLabel }}</FdsMeta>
    </span>
  </button>
</template>
