<script setup lang="ts">
import { computed, ref } from 'vue'
import { useFormFieldNavigation } from '../composables/useFormFieldNavigation'

export interface KsMoneyFieldProps {
  modelValue: number | null
  label: string
  currency?: string
  currencyPosition?: 'left' | 'right'
  disabled?: boolean
  readonly?: boolean
  required?: boolean
  error?: string
  help?: string
  min?: number
  max?: number
  placeholder?: string
  inputId?: string
  size?: 'sm' | 'md' | 'lg'
  locale?: string
}

const props = withDefaults(defineProps<KsMoneyFieldProps>(), {
  currency: 'KRW',
  currencyPosition: 'right',
  disabled: false,
  readonly: false,
  required: false,
  size: 'md',
  locale: 'en-US',
})

const emit = defineEmits<{
  'update:modelValue': [value: number | null]
  blur: [event: FocusEvent]
  focus: [event: FocusEvent]
  change: [value: number | null]
}>()

const isFocused = ref(false)
const id = computed(() => props.inputId || `money-${Math.random().toString(36).substr(2, 9)}`)

const displayValue = computed(() => {
  if (props.modelValue === null || props.modelValue === undefined) return ''
  return new Intl.NumberFormat(props.locale, {
    style: 'currency',
    currency: props.currency,
  }).format(props.modelValue)
})

const containerClass = computed(() => [
  'ks-money-field',
  `ks-money-field--${props.size}`,
  {
    'ks-money-field--focused': isFocused.value,
    'ks-money-field--filled': props.modelValue !== null && props.modelValue !== undefined && props.modelValue !== 0,
    'ks-money-field--disabled': props.disabled,
    'ks-money-field--error': !!props.error,
    'ks-money-field--required': props.required,
  },
])

const handleInput = (event: Event) => {
  const target = event.target as HTMLInputElement
  const value = target.value === '' ? null : parseFloat(target.value.replace(/[^\d.-]/g, ''))

  if (value !== null && !isNaN(value)) {
    emit('update:modelValue', value)
    emit('change', value)
  } else if (value === null) {
    emit('update:modelValue', null)
    emit('change', null)
  }
}

const handleFocus = (event: FocusEvent) => {
  isFocused.value = true
  emit('focus', event)
}

const handleBlur = (event: FocusEvent) => {
  isFocused.value = false
  emit('blur', event)
}

const { inputRef, handleKeyDown } = useFormFieldNavigation()

const handleKeyPress = (event: KeyboardEvent) => {
  handleKeyDown(event, false)
}
</script>

<template>
  <div :class="containerClass">
    <!-- Label -->
    <label :for="id" class="ks-money-field__label">
      {{ label }}
      <span v-if="required" class="ks-money-field__required">*</span>
    </label>

    <!-- Input container -->
    <div class="ks-money-field__container">
      <!-- Currency prefix -->
      <span v-if="currencyPosition === 'left'" class="ks-money-field__currency ks-money-field__currency--left">
        {{ currency }}
      </span>

      <!-- Input -->
      <input
        ref="inputRef"
        :id="id"
        type="number"
        :value="modelValue ?? ''"
        :disabled="disabled"
        :readonly="readonly"
        :required="required"
        :min="min"
        :max="max"
        :placeholder="placeholder"
        class="ks-money-field__input"
        :aria-invalid="!!error"
        :aria-describedby="error || help ? `${id}-hint` : undefined"
        @input="handleInput"
        @focus="handleFocus"
        @blur="handleBlur"
        @keydown="handleKeyPress"
      />

      <!-- Currency suffix -->
      <span v-if="currencyPosition === 'right'" class="ks-money-field__currency ks-money-field__currency--right">
        {{ currency }}
      </span>
    </div>

    <!-- Error or help text -->
    <div v-if="error || help" :id="`${id}-hint`" :class="{ 'ks-money-field__error': error, 'ks-money-field__help': help }">
      {{ error || help }}
    </div>
  </div>
</template>

<style scoped>
.ks-money-field {
  display: flex;
  flex-direction: column;
  gap: var(--spacing-2);
}

.ks-money-field--sm {
  --input-height: 32px;
  --font-size: var(--font-size-sm);
}

.ks-money-field--md {
  --input-height: 36px;
  --font-size: var(--font-size-sm);
}

.ks-money-field--lg {
  --input-height: 44px;
  --font-size: var(--font-size-base);
}

/* Label */
.ks-money-field__label {
  display: flex;
  align-items: center;
  gap: var(--spacing-1);
  font-weight: var(--font-weight-medium);
  color: var(--color-text-primary);
  font-size: var(--font-size-sm);
  cursor: pointer;
}

.ks-money-field__required {
  color: var(--color-danger-500);
}

/* Container */
.ks-money-field__container {
  display: flex;
  align-items: center;
  border: 1px solid var(--color-border-primary);
  border-radius: var(--border-radius-sm);
  background-color: var(--color-background-primary);
  transition: all var(--transition-normal);
  overflow: hidden;
  padding: 0 var(--spacing-2);
}

/* Currency badge */
.ks-money-field__currency {
  font-weight: var(--font-weight-semibold);
  color: var(--color-text-secondary);
  font-size: 0.875rem;
  white-space: nowrap;
  flex-shrink: 0;
}

.ks-money-field__currency--left {
  margin-right: var(--spacing-1);
}

.ks-money-field__currency--right {
  margin-left: var(--spacing-1);
}

/* Input */
.ks-money-field__input {
  flex: 1;
  height: var(--input-height);
  border: none;
  background: transparent;
  font-size: var(--font-size);
  color: var(--color-text-primary);
  outline: none;
  font-family: inherit;
  text-align: right;
  padding: 0;
}

.ks-money-field__input::-webkit-outer-spin-button,
.ks-money-field__input::-webkit-inner-spin-button {
  -webkit-appearance: none;
  margin: 0;
}

.ks-money-field__input[type='number'] {
  -moz-appearance: textfield;
}

.ks-money-field__input::placeholder {
  color: var(--color-text-tertiary);
}

/* Focus state */
.ks-money-field--focused .ks-money-field__container {
  border-color: var(--color-primary-500);
  box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1);
}

/* Disabled state */
.ks-money-field--disabled .ks-money-field__container {
  background-color: var(--color-background-secondary);
  opacity: 0.6;
  cursor: not-allowed;
}

.ks-money-field--disabled .ks-money-field__input {
  cursor: not-allowed;
}

/* Error state */
.ks-money-field--error .ks-money-field__container {
  border-color: var(--color-danger-500);
  box-shadow: 0 0 0 3px rgba(239, 68, 68, 0.1);
}

.ks-money-field--error .ks-money-field__label {
  color: var(--color-danger-500);
}

/* Error text */
.ks-money-field__error {
  font-size: var(--font-size-xs);
  color: var(--color-danger-500);
}

/* Help text */
.ks-money-field__help {
  font-size: var(--font-size-xs);
  color: var(--color-text-secondary);
}
</style>
