<template>
  <div
    class="relative mt-4 flex h-12 w-full items-center"
    :class="[minWidth, maxWidth]"
  >
    <input
      :id="inputId"
      v-maska="mask"
      :name="name"
      :autocomplete="autocomplete"
      class="floating-input grow-height peer min-h-[40px] w-full border bg-white pl-3 pr-3 py-1 outline-none placeholder:text-transparent focus:border-2 "
      :class="[
      disabled ? 'cursor-not-allowed text-black/60 [&:not(:placeholder-shown)]:border-m-muted border-m-muted' : 'cursor-text',
      hasError
        ? 'border-m-error focus:border-m-error [&:not(:placeholder-shown)]:border-m-error'
        : hasSuccess
          ? 'border-m-success focus:border-m-success [&:not(:placeholder-shown)]:border-m-success'
          : 'border-m-muted focus:border-m-primary',
      textInput,
      iconInputPaddingClass,
      focusPaddingClass,
      rounded,
    ]"
      :required="required"
      :maxlength="maxLength"
      :minlength="minLength"
      :disabled="disabled"
      :value="currentValue"
      :readonly="readonly"
      :aria-invalid="!!error"
      :aria-describedby="describedBy"
      v-bind="attrs"
      placeholder="_"
      type="text"
      @input="onInput"
      @focus="isFocused = true"
      @blur="isFocused = false"
    >

    <label
      v-if="label"
      :for="inputId"
      class="floating-label absolute top-2 mt-1 inline-block origin-left transition-transform duration-150 font-medium"
      :class="[
    labelPositionClass,
    shouldFloatLabel ? '-translate-y-[1.15rem] scale-90' : '',
    disabled ? 'peer-[&:not(:placeholder-shown):not(:focus)]:text-black/60' : '',
    hasError
      ? 'text-m-error'
      : hasSuccess
        ? 'text-m-success'
        : 'peer-placeholder-shown:text-m-muted peer-[&:not(:placeholder-shown):not(:focus)]:text-black peer-focus:text-m-primary',
      textLabel,
      ]"
    >
      {{ label }}
    </label>

    <IconifyIcon
      v-if="iconName"
      :icon="iconName"
      :width="iconSize"
      :height="iconSize"
      data-test="icon"
      :class="[
      hasError ? 'text-m-error' : hasSuccess ? 'text-m-success' : '',
      iconPositionClass,
      iconColor,
    ]"
    />

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

<script setup lang="ts">

import type {MaskInputOptions} from 'maska'
import {vMaska} from 'maska/vue'
import {computed, ref, useAttrs, useId} from 'vue'
import { Icon as IconifyIcon } from '@iconify/vue'

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

const props = withDefaults(
  defineProps<{
    id?: string
    label?: string
    name?: string
    autocomplete?: string
    modelValue?: string | null | undefined
    minWidth?: string
    maxWidth?: string
    textInput?: string
    textLabel?: string
    required?: boolean
    maxLength?: number | string
    minLength?: number | string
    disabled?: boolean
    readonly?: boolean
    hint?: string
    error?: string
    success?: string
    iconName?: string
    iconPosition?: 'left' | 'right'
    rounded?: string
    iconSize?: string | number
    iconColor?: string
    mask?: string | MaskInputOptions
  }>(),
  {
    id: '',
    name: '',
    autocomplete: 'off',
    modelValue: undefined,
    iconName: '',
    iconPosition: 'right',
    label: '',
    minWidth: 'w-96',
    maxWidth: '',
    textInput: 'text-lg',
    required: false,
    maxLength: undefined,
    minLength: undefined,
    readonly: false,
    textLabel: 'text-sm',
    disabled: false,
    rounded: 'rounded-md',
    hint: '',
    error: '',
    success: '',
    iconSize: 24,
    iconColor: 'text-m-muted',
    mask: undefined,
  },
)

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

const inputId = computed(() => props.id?.toString() || `malio-input-text-${generatedId}`)
const isControlled = computed(() => props.modelValue !== undefined)
const currentValue = computed(() => (isControlled.value ? (props.modelValue ?? '') : localValue.value))
const shouldFloatLabel = computed(() => isFocused.value || currentValue.value.length > 0)
const hasError = computed(() => !!props.error)
const hasSuccess = computed(() => !!props.success)

const describedBy = computed(() => {
  const ids: string[] = []
  if (props.hint && !hasSuccess.value && !hasError.value) ids.push(`${inputId.value}-hint`)
  if (hasError.value) ids.push(`${inputId.value}-error`)
  if (hasSuccess.value && !hasError.value) ids.push(`${inputId.value}-success`)
  return ids.length ? ids.join(' ') : undefined
})

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

const onInput = (event: Event) => {
  const target = event.target as HTMLInputElement
  if (!isControlled.value) {
    localValue.value = target.value
  }
  emit('update:modelValue', target.value)
}

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

const labelPositionClass = computed(() => {
  if (props.iconName && props.iconPosition === 'left') return 'left-8'
  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-2' : 'right-2'
  return `pointer-events-none absolute ${sideClass} top-1/2 -translate-y-1/2`
})
</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>
