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

export interface SelectOption {
  label: string
  value: any
  disabled?: boolean
  description?: string
}

export interface KsSelectProps {
  modelValue: any
  label?: string
  options: SelectOption[]
  placeholder?: string
  disabled?: boolean
  readonly?: boolean
  required?: boolean
  error?: string
  help?: string
  clearable?: boolean
  searchable?: boolean
  inputId?: string
  size?: 'sm' | 'md' | 'lg'
  inline?: boolean
}

const props = withDefaults(defineProps<KsSelectProps>(), {
  disabled: false,
  readonly: false,
  required: false,
  clearable: true,
  searchable: true,
  size: 'md',
})

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

const isOpen = ref(false)
const isFocused = ref(false)
const searchInput = ref('')
const highlightedIndex = ref(-1)
const id = computed(() => props.inputId || `select-${Math.random().toString(36).substr(2, 9)}`)
const { isInline } = useFieldLayout(props.inline)
const { inputRef, moveToNextField } = useFormFieldNavigation()

const filteredOptions = computed(() => {
  if (!props.searchable || !searchInput.value) return props.options
  const query = searchInput.value.toLowerCase()
  return props.options.filter(opt => opt.label.toLowerCase().includes(query) && !opt.disabled)
})

const selectedOption = computed(() => props.options.find(opt => opt.value === props.modelValue))

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


const handleClick = () => {
  if (props.disabled) return
  isOpen.value = !isOpen.value
  isFocused.value = true
  searchInput.value = ''
  highlightedIndex.value = -1
}

const handleSelect = (option: SelectOption) => {
  if (option.disabled) return
  emit('update:modelValue', option.value)
  emit('change', option.value)
  isOpen.value = false
  isFocused.value = false
  searchInput.value = ''
}

const handleClear = (event: Event) => {
  event.stopPropagation()
  emit('update:modelValue', null)
  emit('change', null)
  searchInput.value = ''
}

const handleKeydown = (event: KeyboardEvent) => {
  switch (event.key) {
    case 'ArrowDown':
      event.preventDefault()
      if (!isOpen.value) {
        isOpen.value = true
      } else {
        highlightedIndex.value = Math.min(highlightedIndex.value + 1, filteredOptions.value.length - 1)
      }
      break
    case 'ArrowUp':
      event.preventDefault()
      if (isOpen.value && highlightedIndex.value > -1) {
        highlightedIndex.value--
      }
      break
    case 'Enter':
      event.preventDefault()
      if (isOpen.value && highlightedIndex.value >= 0) {
        handleSelect(filteredOptions.value[highlightedIndex.value])
        // After selection, move to next field
        setTimeout(() => moveToNextField(), 0)
      } else if (!isOpen.value) {
        // Dropdown closed, move to next field
        moveToNextField()
      }
      break
    case 'Escape':
      event.preventDefault()
      isOpen.value = false
      isFocused.value = false
      break
  }
}

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

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

<template>
  <div :class="containerClass" @keydown="handleKeydown">
    <!-- Label -->
    <label :for="id" class="ks-select__label">
      {{ label }}
      <span v-if="required" class="ks-select__required">*</span>
    </label>

    <!-- Select button -->
    <div class="ks-select__container">
      <button
        ref="inputRef"
        :id="id"
        type="button"
        class="ks-select__button"
        :disabled="disabled"
        :aria-expanded="isOpen"
        :aria-describedby="error || help ? `${id}-hint` : undefined"
        @click="handleClick"
        @focus="handleFocus"
        @blur="handleBlur"
        @keydown="handleKeydown"
      >
        <!-- Selected value or placeholder -->
        <span class="ks-select__value">
          {{ selectedOption?.label || placeholder || 'Select an option' }}
        </span>

        <!-- Clear button -->
        <button
          v-if="clearable && selectedOption && !disabled"
          type="button"
          class="ks-select__clear"
          aria-label="Clear selection"
          @click="handleClear"
        >
          ✕
        </button>

        <!-- Dropdown icon -->
        <span class="ks-select__icon" aria-hidden="true">▼</span>
      </button>

      <!-- Dropdown menu -->
      <div v-if="isOpen" class="ks-select__dropdown" role="listbox">
        <!-- Search input -->
        <div v-if="searchable" class="ks-select__search">
          <input
            v-model="searchInput"
            type="text"
            class="ks-select__search-input"
            placeholder="Search..."
            @click.stop
          />
        </div>

        <!-- Options -->
        <div class="ks-select__options">
          <div v-if="filteredOptions.length === 0" class="ks-select__empty">
            No options available
          </div>

          <button
            v-for="(option, index) in filteredOptions"
            :key="option.value"
            type="button"
            class="ks-select__option"
            :class="{
              'ks-select__option--selected': option.value === modelValue,
              'ks-select__option--highlighted': index === highlightedIndex,
              'ks-select__option--disabled': option.disabled,
            }"
            :disabled="option.disabled"
            role="option"
            :aria-selected="option.value === modelValue"
            @click="handleSelect(option)"
            @mouseenter="highlightedIndex = index"
          >
            <span class="ks-select__option-label">{{ option.label }}</span>
            <span v-if="option.description" class="ks-select__option-desc">{{ option.description }}</span>
            <span v-if="option.value === modelValue" class="ks-select__option-check" aria-hidden="true">✓</span>
          </button>
        </div>
      </div>
    </div>

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

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

.ks-select--inline {
  flex-direction: row;
  align-items: center;
  gap: var(--ks-space-2, 6px);
}

.ks-select--inline .ks-select__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-select--inline .ks-select__container {
  flex: 1 1 auto;
  min-width: 0;
  max-width: 100%;
  width: 100%;
}




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

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

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

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

/* Container */
.ks-select__container {
  position: relative;
}

/* Select button */
.ks-select__button {
  display: flex;
  align-items: center;
  justify-content: space-between;
  width: 100%;
  height: var(--input-height);
  padding: 0 var(--spacing-3);
  border: 1px solid var(--color-border-primary);
  border-radius: var(--border-radius-sm);
  background-color: var(--color-background-primary);
  color: var(--color-text-primary);
  font-size: var(--font-size);
  cursor: pointer;
  transition: all var(--transition-normal);
  font-family: inherit;
}

.ks-select__button:hover:not(:disabled) {
  border-color: var(--color-border-secondary);
}

.ks-select__button:focus {
  outline: none;
  border-color: var(--color-primary-500);
  box-shadow: 0 0 0 3px rgba(59, 130, 246, 0.1);
}

.ks-select__button:disabled {
  opacity: 0.6;
  cursor: not-allowed;
}

/* Value */
.ks-select__value {
  flex: 1;
  text-align: left;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

/* Icons */
.ks-select__icon {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  margin-left: var(--spacing-2);
  transition: transform var(--transition-normal);
  font-size: 0.75rem;
  color: var(--color-text-secondary);
}

.ks-select--open .ks-select__icon {
  transform: rotate(180deg);
}

.ks-select__clear {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  width: 24px;
  height: 24px;
  padding: 0;
  margin: 0 var(--spacing-1);
  border: none;
  background: transparent;
  color: var(--color-text-tertiary);
  cursor: pointer;
  border-radius: var(--border-radius-sm);
  transition: all var(--transition-normal);
}

.ks-select__clear:hover {
  background-color: var(--color-background-secondary);
  color: var(--color-text-secondary);
}

/* Error state */
.ks-select--error .ks-select__button {
  border-color: var(--color-danger-500);
}

.ks-select--error .ks-select__label {
  color: var(--color-danger-500);
}

/* Dropdown menu */
.ks-select__dropdown {
  position: absolute;
  top: calc(100% + var(--spacing-1));
  left: 0;
  right: 0;
  background-color: var(--color-background-primary);
  border: 1px solid var(--color-border-primary);
  border-radius: var(--border-radius-sm);
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
  z-index: 1000;
  overflow: hidden;
  animation: slideDown var(--transition-normal);
}

@keyframes slideDown {
  from {
    opacity: 0;
    transform: translateY(-8px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

/* Search input */
.ks-select__search {
  padding: var(--spacing-2);
  border-bottom: 1px solid var(--color-border-primary);
}

.ks-select__search-input {
  width: 100%;
  height: 32px;
  padding: 0 var(--spacing-2);
  border: 1px solid var(--color-border-primary);
  border-radius: var(--border-radius-sm);
  font-size: var(--font-size-sm);
  font-family: inherit;
}

.ks-select__search-input:focus {
  outline: none;
  border-color: var(--color-primary-500);
}

/* Options */
.ks-select__options {
  max-height: 300px;
  overflow-y: auto;
}

.ks-select__empty {
  padding: var(--spacing-3);
  text-align: center;
  color: var(--color-text-secondary);
  font-size: var(--font-size-sm);
}

/* Option item */
.ks-select__option {
  display: flex;
  align-items: center;
  justify-content: space-between;
  width: 100%;
  padding: var(--spacing-2) var(--spacing-3);
  border: none;
  background: transparent;
  color: var(--color-text-primary);
  font-size: var(--font-size-sm);
  cursor: pointer;
  transition: background-color var(--transition-normal);
  font-family: inherit;
  text-align: left;
}

.ks-select__option:hover:not(:disabled) {
  background-color: var(--color-background-secondary);
}

.ks-select__option--highlighted {
  background-color: var(--color-background-secondary);
}

.ks-select__option--selected {
  background-color: rgba(59, 130, 246, 0.1);
  color: var(--color-primary-600);
  font-weight: var(--font-weight-medium);
}

.ks-select__option--disabled {
  opacity: 0.5;
  cursor: not-allowed;
}

.ks-select__option-label {
  flex: 1;
}

.ks-select__option-desc {
  display: block;
  font-size: var(--font-size-xs);
  color: var(--color-text-secondary);
  margin-top: 2px;
}

.ks-select__option-check {
  margin-left: var(--spacing-2);
  color: var(--color-primary-500);
}

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

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