<template>
  <DatePicker
    v-model="dateModel"
    :input-id="inputId"
    class="localized-date-picker"
    :date-format="dateFormat"
    :placeholder="placeholder"
    :input-class="inputClass"
    :pt="datePickerPt"
    :invalid="invalid"
    :disabled="disabled"
    :required="required"
    show-icon
    icon-display="input"
    append-to="body"
    :panel-class="panelClass"
  />
</template>

<script setup lang="ts">
import DatePicker from 'primevue/datepicker'
import { usePrimeVue } from 'primevue/config'
import { computed, watch } from 'vue'
import { useI18n } from 'vue-i18n'

import {
  formatDatePickerValue,
  normalizeDatePickerLocale,
  parseDatePickerValue,
  primeVueDatePickerLocales,
} from '@/utils/localizedDatePicker'

const props = withDefaults(defineProps<{
  modelValue: string
  inputId: string
  name?: string
  testId: string
  panelTestId?: string
  dateFormat?: string
  placeholder?: string
  inputClass?: string | Record<string, boolean>
  invalid?: boolean
  describedBy?: string
  disabled?: boolean
  required?: boolean
  panelClass?: string
}>(), {
  name: undefined,
  panelTestId: undefined,
  dateFormat: 'yy-mm-dd',
  placeholder: '',
  inputClass: undefined,
  invalid: false,
  describedBy: undefined,
  disabled: false,
  required: false,
  panelClass: 'localized-date-picker-panel',
})

const emit = defineEmits<{
  'update:modelValue': [value: string]
}>()

const { locale } = useI18n()
const primeVue = usePrimeVue()

const dateModel = computed<Date | null>({
  get: () => parseDatePickerValue(props.modelValue),
  set: (value) => {
    emit('update:modelValue', formatDatePickerValue(value))
  },
})

const datePickerPt = computed(() => ({
  pcInputText: {
    root: {
      name: props.name,
      'data-testid': props.testId,
      lang: locale.value,
      'aria-invalid': props.invalid ? 'true' : undefined,
      'aria-describedby': props.describedBy,
    },
  },
  panel: {
    lang: locale.value,
    'data-testid': props.panelTestId ?? `${props.testId}-panel`,
  },
}))

watch(
  locale,
  (nextLocale) => {
    const supportedLocale = normalizeDatePickerLocale(nextLocale)
    primeVue.config.locale = {
      ...(primeVue.config.locale ?? primeVueDatePickerLocales['en-US']),
      ...primeVueDatePickerLocales[supportedLocale],
    }
  },
  { immediate: true },
)
</script>

<style scoped>
.localized-date-picker {
  display: block;
  width: 100%;
}

.localized-date-picker :deep(.p-inputtext) {
  width: 100%;
  padding-right: 40px;
}

.localized-date-picker :deep(.p-datepicker-input-icon-container) {
  right: 12px;
  color: var(--th-color-navy-950);
}
</style>

<style>
.localized-date-picker-panel {
  z-index: 1200;
  color: var(--th-color-navy-950);
  font-family: inherit;
}
</style>
