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

export interface KsDateFieldProps {
  modelValue: string | Date | null
  label?: string
  type?: 'date' | 'datetime' | 'range'
  disabled?: boolean
  readonly?: boolean
  required?: boolean
  error?: string
  help?: string
  min?: Date | string
  max?: Date | string
  placeholder?: string
  inputId?: string
  size?: 'sm' | 'md' | 'lg'
}

const props = withDefaults(defineProps<KsDateFieldProps>(), {
  type: 'date',
  disabled: false,
  readonly: false,
  required: false,
  size: 'md',
})

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

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

const inputRef = ref<HTMLInputElement | null>(null)

const dateString = computed(() => {
  if (!props.modelValue) return ''
  const date = typeof props.modelValue === 'string' ? new Date(props.modelValue) : props.modelValue
  if (isNaN(date.getTime())) return ''
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  return `${year}-${month}-${day}`
})

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

const handleInput = (event: Event) => {
  const target = event.target as HTMLInputElement
  if (!target.value) {
    emit('update:modelValue', null)
    emit('change', null)
    return
  }
  const date = new Date(target.value)
  if (!isNaN(date.getTime())) {
    emit('update:modelValue', date)
    emit('change', date)
  }
}

const openPicker = () => {
  if (props.disabled || props.readonly) return
  if (inputRef.value && typeof inputRef.value.showPicker === 'function') {
    inputRef.value.showPicker()
  } else if (inputRef.value) {
    inputRef.value.focus()
  }
}

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

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

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

    <!-- Input -->
    <div class="ks-date-field__container">
      <input
        :id="id"
        ref="inputRef"
        :type="type === 'range' ? 'text' : type"
        :value="dateString"
        :disabled="disabled"
        :readonly="readonly"
        :required="required"
        :min="typeof min === 'string' ? min : min?.toISOString().split('T')[0]"
        :max="typeof max === 'string' ? max : max?.toISOString().split('T')[0]"
        :placeholder="placeholder"
        class="ks-date-field__input"
        :aria-invalid="!!error"
        :aria-describedby="error || help ? `${id}-hint` : undefined"
        @input="handleInput"
        @focus="handleFocus"
        @blur="handleBlur"
      />
      <span class="ks-date-field__icon" @click="openPicker">📅</span>
    </div>

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

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

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

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

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

/* Label */
.ks-date-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-date-field__required {
  color: var(--color-danger-500);
}

/* Container */
.ks-date-field__container {
  position: relative;
  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);
}

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

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

/* Icon */
.ks-date-field__icon {
  position: absolute;
  right: var(--spacing-3);
  font-size: 1.2rem;
  cursor: pointer;
  color: var(--color-text-tertiary);
}

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

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

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

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

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

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

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