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

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

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

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

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

const isOpen = ref(false)
const searchInput = ref('')
const id = computed(() => props.inputId || `multi-select-${Math.random().toString(36).substr(2, 9)}`)

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 selectedOptions = computed(() => props.options.filter(opt => props.modelValue.includes(opt.value)))

const containerClass = computed(() => [
  'ks-multi-select',
  `ks-multi-select--${props.size}`,
  {
    'ks-multi-select--open': isOpen.value,
    'ks-multi-select--filled': props.modelValue.length > 0,
    'ks-multi-select--disabled': props.disabled,
    'ks-multi-select--error': !!props.error,
    'ks-multi-select--required': props.required,
  },
])

const handleSelect = (option: SelectOption) => {
  if (option.disabled) return

  let newValue
  if (props.modelValue.includes(option.value)) {
    newValue = props.modelValue.filter(v => v !== option.value)
  } else {
    if (props.maxSelections && props.modelValue.length >= props.maxSelections) {
      return
    }
    newValue = [...props.modelValue, option.value]
  }

  emit('update:modelValue', newValue)
  emit('change', newValue)
}

const handleRemove = (value: any, event: Event) => {
  event.stopPropagation()
  const newValue = props.modelValue.filter(v => v !== value)
  emit('update:modelValue', newValue)
  emit('change', newValue)
}

const handleClearAll = (event: Event) => {
  event.stopPropagation()
  emit('update:modelValue', [])
  emit('change', [])
}

const handleClick = () => {
  if (!props.disabled) {
    isOpen.value = !isOpen.value
    searchInput.value = ''
  }
}

const { inputRef, moveToNextField } = useFormFieldNavigation()

const handleKeydown = (event: KeyboardEvent) => {
  if (event.key === 'Escape') {
    isOpen.value = false
  } else if (event.key === 'Enter' && !isOpen.value) {
    event.preventDefault()
    moveToNextField()
  }
}
</script>

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

    <!-- Button -->
    <div class="ks-multi-select__container">
      <button
        ref="inputRef"
        :id="id"
        type="button"
        class="ks-multi-select__button"
        :disabled="disabled"
        :aria-expanded="isOpen"
        :aria-describedby="error || help ? `${id}-hint` : undefined"
        @click="handleClick"
      >
        <!-- Selected tags or placeholder -->
        <div v-if="selectedOptions.length > 0" class="ks-multi-select__tags">
          <span v-for="option in selectedOptions" :key="option.value" class="ks-multi-select__tag">
            {{ option.label }}
            <button
              type="button"
              class="ks-multi-select__tag-remove"
              aria-label="Remove"
              @click="handleRemove(option.value, $event)"
            >
              ✕
            </button>
          </span>
        </div>
        <span v-else class="ks-multi-select__placeholder">{{ placeholder || 'Select options' }}</span>

        <!-- Clear button -->
        <button
          v-if="clearable && selectedOptions.length > 0 && !disabled"
          type="button"
          class="ks-multi-select__clear"
          aria-label="Clear all"
          @click="handleClearAll"
        >
          ✕
        </button>

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

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

        <!-- Options -->
        <div class="ks-multi-select__options">
          <button
            v-for="option in filteredOptions"
            :key="option.value"
            type="button"
            class="ks-multi-select__option"
            :class="{
              'ks-multi-select__option--selected': modelValue.includes(option.value),
              'ks-multi-select__option--disabled': option.disabled,
            }"
            :disabled="option.disabled"
            role="option"
            @click="handleSelect(option)"
          >
            <input
              type="checkbox"
              :checked="modelValue.includes(option.value)"
              :disabled="option.disabled"
              class="ks-multi-select__checkbox"
              :aria-label="option.label"
            />
            <span class="ks-multi-select__option-label">{{ option.label }}</span>
          </button>
        </div>
      </div>
    </div>

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

    <!-- Selection count -->
    <div v-if="selectedOptions.length > 0" class="ks-multi-select__count">
      {{ selectedOptions.length }} selected
    </div>
  </div>
</template>

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

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

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

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

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

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

/* Button */
.ks-multi-select__button {
  display: flex;
  align-items: center;
  justify-content: space-between;
  width: 100%;
  min-height: var(--input-height);
  padding: var(--spacing-2) 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;
  gap: var(--spacing-2);
}

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

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

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

/* Tags */
.ks-multi-select__tags {
  display: flex;
  flex-wrap: wrap;
  gap: var(--spacing-1);
  flex: 1;
}

.ks-multi-select__tag {
  display: inline-flex;
  align-items: center;
  gap: var(--spacing-1);
  padding: 2px var(--spacing-2);
  background-color: var(--color-primary-100);
  color: var(--color-primary-700);
  border-radius: var(--border-radius-sm);
  font-size: 0.875rem;
  font-weight: var(--font-weight-medium);
}

.ks-multi-select__tag-remove {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  width: 16px;
  height: 16px;
  padding: 0;
  border: none;
  background: transparent;
  color: inherit;
  cursor: pointer;
  border-radius: 2px;
}

.ks-multi-select__tag-remove:hover {
  background-color: rgba(0, 0, 0, 0.1);
}

/* Placeholder */
.ks-multi-select__placeholder {
  color: var(--color-text-tertiary);
}

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

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

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

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

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

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

/* Dropdown */
.ks-multi-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 */
.ks-multi-select__search {
  padding: var(--spacing-2);
  border-bottom: 1px solid var(--color-border-primary);
}

.ks-multi-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-multi-select__search-input:focus {
  outline: none;
  border-color: var(--color-primary-500);
}

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

.ks-multi-select__option {
  display: flex;
  align-items: center;
  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;
  gap: var(--spacing-2);
}

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

.ks-multi-select__option--selected {
  background-color: rgba(59, 130, 246, 0.1);
}

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

.ks-multi-select__checkbox {
  flex-shrink: 0;
}

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

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

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

/* Count */
.ks-multi-select__count {
  font-size: var(--font-size-xs);
  color: var(--color-text-secondary);
  text-align: right;
}
</style>
