<script setup lang="ts">
import { ArrowDown } from '@element-plus/icons-vue'
import { ElInputNumber, ElPopover } from 'element-plus'
import { computed } from 'vue'
import { rangeLabel, isRangeSelected } from '@/features/listings/composables/useFilterOptions'

interface RangeOption {
  label: string
  min: number | undefined
  max: number | undefined
}

interface Props {
  label: string
  modelMin: number | undefined
  modelMax: number | undefined
  options: RangeOption[]
  popoverProps: Record<string, any>
  wide?: boolean
}

const props = defineProps<Props>()

const emit = defineEmits<{
  'update:modelMin': [value: number | undefined]
  'update:modelMax': [value: number | undefined]
  close: []
}>()

const minValue = computed({
  get: () => props.modelMin,
  set: (val) => emit('update:modelMin', val),
})

const maxValue = computed({
  get: () => props.modelMax,
  set: (val) => emit('update:modelMax', val),
})

const isActive = computed(() => {
  return props.modelMin !== undefined || props.modelMax !== undefined
})

const chipLabel = computed(() => {
  return rangeLabel(props.modelMin, props.modelMax, props.label)
})

function selectRange(min: number | undefined, max: number | undefined) {
  emit('update:modelMin', min)
  emit('update:modelMax', max)
  emit('close')
}

function isSelected(item: RangeOption) {
  return isRangeSelected(props.modelMin, props.modelMax, item.min, item.max)
}
</script>

<template>
  <el-popover v-bind="popoverProps" :width="350">
    <template #reference>
      <button
        class="filter-chip"
        :class="{ active: isActive, wide }"
        type="button"
      >
        <span>{{ chipLabel }}</span>
        <el-icon><ArrowDown /></el-icon>
      </button>
    </template>
    <div class="range-menu">
      <button
        v-for="item in options"
        :key="item.label"
        type="button"
        :class="{ active: isSelected(item) }"
        @click="selectRange(item.min, item.max)"
      >
        {{ item.label }}
      </button>
      <div class="range-manual">
        <el-input-number
          v-model="minValue"
          :controls="false"
          :min="0"
          placeholder="最小值"
        />
        <span>-</span>
        <el-input-number
          v-model="maxValue"
          :controls="false"
          :min="0"
          placeholder="最大值"
        />
      </div>
    </div>
  </el-popover>
</template>

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