<template>
  <div>
    <div
      :class="mergedGroupClass"
    >
      <input
        :id="inputId"
        :name="name"
        :autocomplete="autocomplete"
        :class="mergedInputClass"
        :required="required"
        :minlength="minLength"
        :disabled="disabled"
        :value="formattedValue"
        :readonly="readonly"
        :aria-invalid="!!error"
        :aria-describedby="describedBy"
        v-bind="attrs"
        type="text"
        inputmode="decimal"
        placeholder="_"
        @input="onInput"
        @focus="isFocused = true"
        @blur="onBlur"
      >

      <label
        v-if="label"
        :for="inputId"
        :class="mergedLabelClass"
      >
        {{ label }}<MalioRequiredMark v-if="required" />
      </label>

      <IconifyIcon
        v-if="iconName"
        :icon="iconName"
        :width="iconSize"
        :height="iconSize"
        data-test="icon"
        :class="[iconStateClass, iconPositionClass]"
      />

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

<script setup lang="ts">
import {computed, ref, useAttrs, useId} from 'vue'
import { Icon as IconifyIcon } from '@iconify/vue'
import {twMerge} from 'tailwind-merge'
import MalioRequiredMark from '../shared/RequiredMark.vue'
import {normalizeAmount, formatGroupedAmount, countSignificant, caretFromSignificant} from './composables/amountFormat'

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

const props = withDefaults(
  defineProps<{
    id?: string
    label?: string
    name?: string
    autocomplete?: string
    modelValue?: string | null | undefined
    inputClass?: string
    labelClass?: string
    groupClass?: string
    required?: boolean
    maxLength?: number | string
    minLength?: number | string
    disabled?: boolean
    readonly?: boolean
    hint?: string
    error?: string
    success?: string
    iconName?: string
    iconPosition?: 'left' | 'right'
    iconSize?: string | number
    iconColor?: string
    reserveMessageSpace?: boolean
  }>(),
  {
    id: '',
    name: '',
    autocomplete: 'off',
    modelValue: undefined,
    iconName: 'mdi:currency-eur',
    iconPosition: 'right',
    label: '',
    inputClass: '',
    labelClass: '',
    groupClass: '',
    required: false,
    maxLength: undefined,
    minLength: undefined,
    readonly: false,
    disabled: false,
    hint: '',
    error: '',
    success: '',
    iconSize: 20,
    iconColor: 'text-m-muted',
    reserveMessageSpace: true,
  },
)

const attrs = useAttrs()
const generatedId = useId()
const localValue = ref('')
const isFocused = ref(false)

const inputId = computed(() => props.id?.toString() || `malio-input-amount-${generatedId}`)
const isControlled = computed(() => props.modelValue !== undefined)
const currentValue = computed(() => (isControlled.value ? (props.modelValue ?? '') : localValue.value))
const formattedValue = computed(() => formatGroupedAmount(currentValue.value))
const hasError = computed(() => !!props.error)
const hasSuccess = computed(() => !!props.success)
const isFilled = computed(() => currentValue.value.trim().length > 0)
const isReadonly = computed(() => props.readonly && !props.disabled)
const shouldFloatLabel = computed(() =>
  isReadonly.value
    ? isFilled.value
    : isFocused.value || currentValue.value.length > 0,
)

const mergedGroupClass = computed(() =>
  twMerge(
    'relative flex h-12 w-full items-center',
    props.groupClass,
  ),
)
const mergedInputClass = computed(() =>
  twMerge(
    'floating-input peer min-h-[40px] w-full border bg-white pl-3 pr-3 py-1 outline-none placeholder:text-transparent text-lg rounded-md',
    isReadonly.value ? '' : 'grow-height',
    isReadonly.value
      ? 'border-black'
      : isFilled.value ? 'border-black' : 'border-m-muted',
    disabled.value ? 'cursor-not-allowed text-black/60 [&:not(:placeholder-shown)]:border-m-muted border-m-muted' : 'cursor-text',
    hasError.value
      ? 'border-m-danger focus:border-m-danger [&:not(:placeholder-shown)]:border-m-danger'
      : hasSuccess.value
        ? 'border-m-success focus:border-m-success [&:not(:placeholder-shown)]:border-m-success'
        : isReadonly.value ? '' : 'focus:border-m-primary',
    isReadonly.value ? 'cursor-default' : '',
    props.inputClass,
    iconInputPaddingClass.value,
    isReadonly.value ? '' : focusPaddingClass.value,
  ),
)
const mergedLabelClass = computed(() =>
  twMerge(
    'floating-label absolute top-2 mt-[5px] inline-block origin-left transition-transform duration-150 font-medium text-sm',
    labelPositionClass.value,
    shouldFloatLabel.value
      ? `-translate-y-[1.25rem] scale-90${isReadonly.value ? '' : ' peer-focus:-translate-y-[1.55rem]'}`
      : '',
    hasError.value
      ? 'text-m-danger'
      : hasSuccess.value
        ? 'text-m-success'
        : disabled.value
          ? 'text-m-muted'
          : isReadonly.value
            ? isFilled.value ? 'text-black' : 'text-m-muted'
            : 'peer-placeholder-shown:text-m-muted peer-[&:not(:placeholder-shown):not(:focus)]:text-black peer-focus:text-m-primary',
    props.labelClass,
  ),
)

const describedBy = computed(() => {
  if (!props.hint && !hasError.value && !hasSuccess.value) return undefined
  return `${inputId.value}-describedby`
})

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

// À la frappe : parse vers le modèle propre (émis), reformate l'affichage groupé, repositionne le curseur.
const onInput = (event: Event) => {
  const target = event.target as HTMLInputElement
  const rawText = target.value
  const caret = target.selectionStart ?? rawText.length
  const model = normalizeAmount(rawText)

  // maxLength borne la longueur du MODÈLE (pas l'affichage) : on ignore le keystroke en dépassement.
  if (props.maxLength != null && model.length > Number(props.maxLength)) {
    target.value = formattedValue.value
    const restored = Math.max(0, caret - 1)
    target.setSelectionRange(restored, restored)
    return
  }

  const display = formatGroupedAmount(model)
  const sig = countSignificant(rawText, caret)
  target.value = display
  const newCaret = caretFromSignificant(display, sig)
  target.setSelectionRange(newCaret, newCaret)

  if (!isControlled.value) {
    localValue.value = model
  }
  emit('update:modelValue', model)
}

// Keep the blur handler only for focus-driven UI state.
const onBlur = () => {
  isFocused.value = false
}

const iconInputPaddingClass = computed(() => {
  if (!props.iconName) return ''
  return props.iconPosition === 'left' ? '!pl-11 !pr-3' : ''
})

const disabled = computed(() => props.disabled)

const labelPositionClass = computed(() => {
  if (props.iconName && props.iconPosition === 'left') return 'left-11'
  return 'left-3'
})

const focusPaddingClass = computed(() => {
  if (props.iconName && props.iconPosition === 'left') return 'focus:!pl-11'
  return 'focus:pl-[11px]'
})

const iconPositionClass = computed(() => {
  const sideClass = props.iconPosition === 'left' ? 'left-[10px]' : 'right-[10px]'
  return `pointer-events-none absolute ${sideClass} top-1/2 -translate-y-1/2`
})

const iconStateClass = computed(() => {
  if (hasError.value) return 'text-m-danger'
  if (hasSuccess.value) return 'text-m-success'
  if (disabled.value) return props.iconColor
  if (isReadonly.value) return isFilled.value ? 'text-black' : 'text-m-muted'
  if (isFocused.value) return 'text-m-primary'
  if (isFilled.value) return 'text-black'
  return props.iconColor
})
</script>

<style scoped>
.floating-label {
  background: white;
  padding: 0 0.25rem;
}

.grow-height {
  transition: border-color 160ms ease, box-shadow 160ms ease, padding-top 160ms ease, padding-bottom 160ms ease;
}

.grow-height:focus {
  padding-top: 0.625rem;
  padding-bottom: 0.625rem;
}
@media (prefers-reduced-motion: reduce) {
  .grow-height { transition: none; }
}
</style>
