<script setup lang="ts">
import { ArrowDown } from '@element-plus/icons-vue'
import { ElPopover } from 'element-plus'
import { computed } from 'vue'

interface Props {
  label: string
  placeholder: string
  modelValue: string[]
  options: string[]
  popoverProps: Record<string, any>
  wide?: boolean
}

const props = withDefaults(defineProps<Props>(), {
  modelValue: () => [],
})

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

const selectedValues = computed(() => props.modelValue.filter(Boolean))

const isActive = computed(() => selectedValues.value.length > 0)

const displayLabel = computed(() => {
  const values = selectedValues.value
  if (!values.length) return props.placeholder
  if (values.length === 1) return values[0]
  if (values.length === 2) return values.join('、')
  return `${values[0]} 等${values.length}项`
})

function isSelected(value: string) {
  return selectedValues.value.includes(value)
}

function toggleOption(value: string) {
  if (!value) {
    emit('update:modelValue', [])
    return
  }
  if (isSelected(value)) {
    emit(
      'update:modelValue',
      selectedValues.value.filter(item => item !== value)
    )
    return
  }
  emit('update:modelValue', [...selectedValues.value, value])
}
</script>

<template>
  <el-popover v-bind="popoverProps" :width="220">
    <template #reference>
      <button class="filter-chip" :class="{ active: isActive, wide }" type="button">
        <span>{{ displayLabel }}</span>
        <el-icon><ArrowDown /></el-icon>
      </button>
    </template>
    <div class="filter-menu">
      <button type="button" :class="{ active: !selectedValues.length }" @click="toggleOption('')">
        全部
      </button>
      <button
        v-for="item in options"
        :key="item"
        type="button"
        :class="{ active: isSelected(item) }"
        @click="toggleOption(item)"
      >
        <span class="filter-option-check" :class="{ checked: isSelected(item) }" aria-hidden="true" />
        {{ item }}
      </button>
    </div>
  </el-popover>
</template>

<style src="@/styles/home-filters.css"></style>
