<template>
  <div>
    <div :class="mergedGroupClass">
      <label
        v-if="label"
        :for="hoursInputId"
        :class="mergedLabelClass"
      >
        {{ label }}
      </label>

      <div class="flex items-center gap-2">
        <input
          :id="hoursInputId"
          :name="hoursName"
          autocomplete="off"
          :class="mergedInputClass('hours')"
          :required="required"
          :disabled="disabled"
          :readonly="readonly"
          :aria-invalid="!!error"
          :aria-describedby="describedBy"
          :value="hoursValue"
          v-bind="attrs"
          type="text"
          inputmode="numeric"
          placeholder="00"
          maxlength="2"
          @input="onHoursInput"
          @focus="activeField = 'hours'"
          @blur="onHoursBlur"
        >

        <span class="text-lg text-black">:</span>

        <input
          :id="minutesInputId"
          :name="minutesName"
          autocomplete="off"
          :class="mergedInputClass('minutes')"
          :required="required"
          :disabled="disabled"
          :readonly="readonly"
          :aria-invalid="!!error"
          :aria-describedby="describedBy"
          :value="minutesValue"
          v-bind="attrs"
          type="text"
          inputmode="numeric"
          placeholder="00"
          maxlength="2"
          @input="onMinutesInput"
          @focus="activeField = 'minutes'"
          @blur="onMinutesBlur"
        >
      </div>
    </div>

    <p
      v-if="hint || hasError || hasSuccess"
      :id="`${inputId}-describedby`"
      :class="[
        hasError
          ? 'text-m-error'
          : hasSuccess
            ? 'text-m-success'
            : 'text-m-muted',
        'mt-1 ml-[2px] text-xs',
      ]"
    >
      {{ error || success || hint }}
    </p>
  </div>
</template>

<script setup lang="ts">
import {computed, ref, useAttrs, useId, watch} from 'vue'
import {twMerge} from 'tailwind-merge'

defineOptions({name: 'MalioTime', inheritAttrs: false})

const props = withDefaults(
  defineProps<{
    id?: string
    label?: string
    name?: string
    modelValue?: string | null | undefined
    inputClass?: string
    labelClass?: string
    groupClass?: string
    required?: boolean
    disabled?: boolean
    readonly?: boolean
    hint?: string
    error?: string
    success?: string
  }>(),
  {
    id: '',
    name: '',
    modelValue: undefined,
    label: '',
    inputClass: '',
    labelClass: '',
    groupClass: '',
    required: false,
    readonly: false,
    disabled: false,
    hint: '',
    error: '',
    success: '',
  },
)

const attrs = useAttrs()
const generatedId = useId()
const hoursValue = ref('')
const minutesValue = ref('')
const activeField = ref<'hours' | 'minutes' | null>(null)

const inputId = computed(() => props.id?.toString() || `malio-time-${generatedId}`)
const hoursInputId = computed(() => `${inputId.value}-hours`)
const minutesInputId = computed(() => `${inputId.value}-minutes`)
const hoursName = computed(() => (props.name ? `${props.name}-hours` : ''))
const minutesName = computed(() => (props.name ? `${props.name}-minutes` : ''))
const hasError = computed(() => !!props.error)
const hasSuccess = computed(() => !!props.success && !hasError.value)

const emit = defineEmits<{
  (event: 'update:modelValue', value: string): void
}>()

const padSegment = (value: string) => (value === '' ? '' : value.padStart(2, '0'))

const sanitizeDigits = (value: string) =>
  value.replace(/\D/g, '').slice(0, 2)

const normalizeHours = (value: string) => {
  const digits = sanitizeDigits(value)
  if (digits === '') return ''
  return String(Math.min(Number.parseInt(digits, 10), 23))
}

const normalizeMinutes = (value: string) => {
  const digits = sanitizeDigits(value)
  if (digits === '') return ''
  return String(Math.min(Number.parseInt(digits, 10), 59))
}

const parseTimeValue = (value: string | null | undefined) => {
  if (!value) return {hours: '', minutes: ''}

  const [rawHours = '', rawMinutes = ''] = value.split(':')

  return {
    hours: normalizeHours(rawHours),
    minutes: normalizeMinutes(rawMinutes),
  }
}

const syncFromModelValue = (value: string | null | undefined) => {
  const parsedValue = parseTimeValue(value)
  hoursValue.value = parsedValue.hours
  minutesValue.value = parsedValue.minutes
}

watch(() => props.modelValue, syncFromModelValue, {immediate: true})

const describedBy = computed(() =>
  (props.hint || hasError.value || hasSuccess.value) ? `${inputId.value}-describedby` : undefined,
)

const mergedGroupClass = computed(() =>
  twMerge(
    'relative mt-4 flex w-full items-center',
    props.groupClass,
  ),
)

const mergedLabelClass = computed(() =>
  twMerge(
    'radio-text mt-px mr-3 cursor-pointer text-black',
    hasError.value ? 'text-m-error' : '',
    hasSuccess.value ? 'text-m-success' : '',
    props.disabled ? 'cursor-not-allowed text-black/60' : '',
    props.labelClass
  ),
)

const mergedInputClass = (field: 'hours' | 'minutes') =>
  twMerge(
    'h-7 w-9 border bg-white text-center text-lg outline-none rounded-md placeholder:text-m-muted',
    props.disabled ? 'cursor-not-allowed text-black/60 border-m-muted' : 'cursor-text',
    hasError.value
      ? 'focus:border-2 border-m-error focus:border-m-error'
      : hasSuccess.value
        ? 'focus:border-2 border-m-success focus:border-m-success'
        : activeField.value === field
          ? 'border-2 border-m-primary text-m-primary'
          : 'border-black text-black',
    props.inputClass,
  )

const emitCurrentValue = () => {
  const formattedHours = padSegment(hoursValue.value)
  const formattedMinutes = padSegment(minutesValue.value)

  if (!formattedHours && !formattedMinutes) {
    emit('update:modelValue', '')
    return
  }

  emit('update:modelValue', `${formattedHours}:${formattedMinutes}`)
}

const onHoursInput = (event: Event) => {
  const target = event.target as HTMLInputElement
  const normalizedValue = normalizeHours(target.value)

  hoursValue.value = normalizedValue
  target.value = normalizedValue
  emitCurrentValue()
}

const onMinutesInput = (event: Event) => {
  const target = event.target as HTMLInputElement
  const normalizedValue = normalizeMinutes(target.value)

  minutesValue.value = normalizedValue
  target.value = normalizedValue
  emitCurrentValue()
}

const formatFieldOnBlur = (field: 'hours' | 'minutes') => {
  if (field === 'hours' && hoursValue.value) {
    hoursValue.value = padSegment(hoursValue.value)
  }

  if (field === 'minutes' && minutesValue.value) {
    minutesValue.value = padSegment(minutesValue.value)
  }

  emitCurrentValue()
}

const onHoursBlur = () => {
  formatFieldOnBlur('hours')
  activeField.value = null
}

const onMinutesBlur = () => {
  formatFieldOnBlur('minutes')
  activeField.value = null
}
</script>
