<script setup lang="ts">
import { computed, ref } from 'vue'
import { useFieldLayout } from '../contracts/layoutContext'

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'
  inline?: boolean
  showPresets?: boolean
}

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


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 { isInline } = useFieldLayout(props.inline)

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

const dateString = computed(() => {
  if (!props.modelValue) return ''
  if (typeof props.modelValue === 'string' && props.modelValue.includes('~')) return props.modelValue
  const date = typeof props.modelValue === 'string' ? new Date(props.modelValue) : props.modelValue
  if (isNaN(date.getTime())) return typeof props.modelValue === 'string' ? props.modelValue : ''
  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--inline': isInline.value,
    '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 startDateStr = computed(() => {
  if (!props.modelValue) return '2026-08-08'
  const val = String(props.modelValue)
  if (val.includes('~')) {
    return val.split('~')[0].trim()
  }
  return val
})

const endDateStr = computed(() => {
  if (!props.modelValue) return '2026-08-15'
  const val = String(props.modelValue)
  if (val.includes('~')) {
    return val.split('~')[1].trim()
  }
  return val
})

const handleStartChange = (event: Event) => {
  activePreset.value = null
  const target = event.target as HTMLInputElement
  const newStart = target.value
  const newEnd = endDateStr.value || newStart
  const rangeVal = `${newStart} ~ ${newEnd}`
  emit('update:modelValue', rangeVal)
  emit('change', rangeVal)
}

const handleEndChange = (event: Event) => {
  activePreset.value = null
  const target = event.target as HTMLInputElement
  const newEnd = target.value
  const newStart = startDateStr.value || newEnd
  const rangeVal = `${newStart} ~ ${newEnd}`
  emit('update:modelValue', rangeVal)
  emit('change', rangeVal)
}

const handleInput = (event: Event) => {
  activePreset.value = null
  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 selectPreset = (preset: 'today' | 'yesterday' | '1w' | '1m' | '3m') => {
  if (props.disabled || props.readonly) return
  activePreset.value = preset

  const today = new Date()
  const formatDate = (d: Date) => {
    const y = d.getFullYear()
    const m = String(d.getMonth() + 1).padStart(2, '0')
    const day = String(d.getDate()).padStart(2, '0')
    return `${y}-${m}-${day}`
  }

  let start: Date
  let end: Date = today

  if (preset === 'today') {
    start = today
  } else if (preset === 'yesterday') {
    start = new Date()
    start.setDate(start.getDate() - 1)
    end = new Date(start)
  } else if (preset === '1w') {
    start = new Date()
    start.setDate(start.getDate() - 7)
  } else if (preset === '1m') {
    start = new Date()
    start.setMonth(start.getMonth() - 1)
  } else if (preset === '3m') {
    start = new Date()
    start.setMonth(start.getMonth() - 3)
  } else {
    start = today
  }

  const startStr = formatDate(start)
  const endStr = formatDate(end)

  if (props.type === 'range') {
    const rangeVal = `${startStr} ~ ${endStr}`
    emit('update:modelValue', rangeVal)
    emit('change', rangeVal)
  } else {
    emit('update:modelValue', startStr)
    emit('change', startStr)
  }
}

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>

    <!-- Single Date / DateTime Input -->
    <div v-if="type !== 'range'" class="ks-date-field__container">
      <input
        :id="id"
        ref="inputRef"
        :type="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>

    <!-- Range Selection (From ~ To) Dual Date Inputs with Calendar Pickers -->
    <div v-else class="ks-date-field__container ks-date-range-container">
      <input
        :id="`${id}-start`"
        type="date"
        :value="startDateStr"
        :disabled="disabled"
        :readonly="readonly"
        :required="required"
        class="ks-date-field__input ks-date-range-input"
        aria-label="조회 시작일"
        @change="handleStartChange"
        @focus="handleFocus"
        @blur="handleBlur"
      />
      <span class="ks-date-range-separator">~</span>
      <input
        :id="`${id}-end`"
        type="date"
        :value="endDateStr"
        :disabled="disabled"
        :readonly="readonly"
        :required="required"
        class="ks-date-field__input ks-date-range-input"
        aria-label="조회 종료일"
        @change="handleEndChange"
        @focus="handleFocus"
        @blur="handleBlur"
      />
    </div>

    <!-- Quick Date Preset Buttons -->
    <div v-if="props.showPresets" class="ks-date-presets" aria-label="빠른 날짜 선택 픽커">
      <button type="button" class="ks-date-preset-btn" :class="{ 'ks-date-preset-btn--active': activePreset === 'today' }" @click="selectPreset('today')">오늘</button>
      <button type="button" class="ks-date-preset-btn" :class="{ 'ks-date-preset-btn--active': activePreset === 'yesterday' }" @click="selectPreset('yesterday')">어제</button>
      <button type="button" class="ks-date-preset-btn" :class="{ 'ks-date-preset-btn--active': activePreset === '1w' }" @click="selectPreset('1w')">1주일</button>
      <button type="button" class="ks-date-preset-btn" :class="{ 'ks-date-preset-btn--active': activePreset === '1m' }" @click="selectPreset('1m')">1개월</button>
      <button type="button" class="ks-date-preset-btn" :class="{ 'ks-date-preset-btn--active': activePreset === '3m' }" @click="selectPreset('3m')">3개월</button>
    </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--inline {
  flex-direction: row;
  align-items: center;
  gap: var(--ks-space-2, 6px);
}

.ks-date-field--inline .ks-date-field__label {
  width: var(--ks-field-label-width, 72px);
  min-width: var(--ks-field-label-width, 72px);
  max-width: var(--ks-field-label-width, 72px);
  text-align: left;
  white-space: nowrap;
  flex-shrink: 0;
  margin-bottom: 0;
}

.ks-date-field--inline .ks-date-field__container {
  flex: 1 1 auto;
  min-width: 0;
  max-width: 100%;
  width: 100%;
}


.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);
}

.ks-date-range-container {
  display: flex;
  align-items: center;
  gap: 2px;
  width: 100%;
}

.ks-date-range-input {
  flex: 1;
  min-width: 0;
  padding: 0 2px !important;
  font-size: 11px !important;
}

.ks-date-range-separator {
  color: var(--ks-color-text-muted, #64748b);
  font-weight: 700;
  font-size: 11px;
  user-select: none;
  padding: 0 1px;
}

/* Quick Date Preset Floating Popover Overlay Styles (레이아웃 공간 차지 0px) */
.ks-date-field {
  position: relative;
}

.ks-date-presets {
  position: absolute;
  top: calc(100% + 2px);
  left: 0;
  z-index: 1000;
  display: flex;
  align-items: center;
  gap: var(--ks-space-1, 4px);
  padding: 4px 6px;
  background: var(--ks-color-surface-raised, #ffffff);
  border: 1px solid var(--ks-color-border-strong, #94a3b8);
  border-radius: var(--ks-radius-md, 6px);
  box-shadow: 0 4px 14px rgba(0, 0, 0, 0.15);
  white-space: nowrap;
  opacity: 0;
  visibility: hidden;
  transform: translateY(-2px);
  transition: opacity 0.15s ease, transform 0.15s ease, visibility 0.15s ease;
}

/* Show floating presets popover on hover or focus */
.ks-date-field:hover .ks-date-presets,
.ks-date-field--focused .ks-date-presets,
.ks-date-presets:hover {
  opacity: 1;
  visibility: visible;
  transform: translateY(0);
}

.ks-date-preset-btn {
  padding: 2px 8px;
  font-size: 11px;
  line-height: 14px;
  font-weight: 600;
  color: var(--ks-color-text-muted, #475569);
  background: var(--ks-color-canvas, #f8fafc);
  border: 1px solid var(--ks-color-border, #cbd5e1);
  border-radius: var(--ks-radius-sm, 4px);
  cursor: pointer;
  transition: all 0.15s ease-in-out;
}

.ks-date-preset-btn:hover {
  color: var(--ks-color-action, #0284c7);
  border-color: var(--ks-color-action, #0284c7);
  background: var(--ks-color-surface-raised, #ffffff);
}

.ks-date-preset-btn--active {
  color: #ffffff !important;
  background: var(--ks-color-action, #0284c7) !important;
  border-color: var(--ks-color-action, #0284c7) !important;
}
</style>



